Javascript Regex: How to put a variable inside a regular expression?

So for example:

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 (eg the variable comes from user input)


You can use the RegExp object:

var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);

Then you can construct regexstring in any way you want.

You can read more about it here.


To build a regular expression from a variable in JavaScript, you'll need to use the RegExp constructor with a string parameter.

function reg(input) {
    var flags;
    //could be any combination of 'g', 'i', and 'm'
    flags = 'g';
    return new RegExp('ReGeX' + input + 'ReGeX', flags);
}

of course, this is a very naive example. It assumes that input is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:

function regexEscape(str) {
    return str.replace(/[-/^$*+?.()|[]{}]/g, '$&')
}

function reg(input) {
    var flags;
    //could be any combination of 'g', 'i', and 'm'
    flags = 'g';
    input = regexEscape(input);
    return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
链接地址: http://www.djcxy.com/p/76816.html

上一篇: 使用RegExp匹配括号,然后递增

下一篇: Javascript正则表达式:如何在正则表达式中放置一个变量?