I need to pass variable into RegExp
form = form.replace(/someVar\_\d+/g, someVar+"_"+num)
I read this question, but there is not a combination of regular expression (like \d+
) and a string variable:
How do you use a variable in a regular expression?
And I can use eval
here, but I want to avoid it
You're looking for almost the same thing the question shows:
var r = new RegExp(someVar + "_\\d+","g");
Two minor notes:
- You may want to escape regexp meta-characters that may be present in
someVar
. - Note
"\\d+"
is a string, so you have to escape the backslash.
I'm assuming you are asking how to escape your string so it isn't interpreted as regex.
http://simonwillison.net/2006/Jan/20/escape/ should be what you are looking for then.