I have searched and searched and tried many different options but can not get this to work although I am sure it is possible.
I need to be able to replace a string using a variable as the search and replacing using the matched reference group such as $1
I can search for a variable and I can get the reference to work - but not both at the same time.
The following works great - except it does not preserve the case of “Test” in the string
var q = "test".toLowerCase();
var mystring = "My Test string";
var reg = new RegExp(q, "i");
mystring.replace(reg, "<mark>"+q+"</mark>");
This is the reason I can not simple replace with “q” and need to replace with what was actually found. But this does not work like this:
var q = "test".toLowerCase();
var mystring = "My Test string";
var reg = new RegExp((q), "i");
mystring.replace(reg, "<mark>$1</mark>");
I guess the question is: As “q” is a variable - how do I put parentheses around it so that I can reference it in the replace statement?