Javascript Regex:如何将变量放在正则表达式中? [英] Javascript Regex: How to put a variable inside a regular expression?

查看:113
本文介绍了Javascript Regex:如何将变量放在正则表达式中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

function(input){
    var testVar = input;
    string = ...
    string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}

但这当然不起作用:)
有没有办法做到这一点?

But this is of course not working :) Is there any way to do this?

推荐答案

var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");



更新



根据部分评论,重要的是要注意你可能想要逃避 变量如果存在恶意内容的可能性(例如变量来自用户输入)

Update

Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

这篇关于Javascript Regex:如何将变量放在正则表达式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆