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?
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?
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).
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
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.