Grouped regEx replacement with variable?

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?

The $1 provides the first captured string. You have not yet specified any captured group in your regular expression. You do that with parenthesis in your regex

For example:


var reg = new RegExp('(' + q + ')', "i");