views:

27

answers:

3

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?

A: 

You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.

You can also use RegExp constructor to pass flags in (see the docs).

Nikita Rybak
+6  A: 
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
Jason McCreary
+1  A: 

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.

steinar
+1 for the full sample, RegExp params, and link.
Jason McCreary