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

Solution 1:

const 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)

ES6 Update

In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:

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

Solution 2:

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.

Solution 3:

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);
}

Solution 4:

You can create regular expressions in JS in one of two ways:

  1. Using regular expression literal - /ab{2}/g
  2. Using the regular expression constructor - new RegExp("ab{2}", "g") .

Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is

new RegExp(regularExpressionString, modifiersString)

You can embed variables as part of the regularExpressionString. For example,

var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g") 

This will match any appearance of the pattern cdcdcd.

Solution 5:

if you're using es6 template literals are an option...

string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")