Results 1 to 2 of 2
Oct 1, 2010, 01:49 #1
- Join Date
- Jun 2006
- 0 Post(s)
- 0 Thread(s)
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?
Oct 1, 2010, 05:06 #2
- Join Date
- Jan 2007
- Christchurch, New Zealand
- 76 Post(s)
- 3 Thread(s)
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
var reg = new RegExp('(' + q + ')', "i");