Possible Duplicate:
Escape string for use in Javascript regex
I have a msg like this:
Max {0} chars allowed in {1}
And I have a function to create a message using the arguments passed as
for(var i = 0; i < agrs.length; i++){ reg = new RegExp('\{'+i+'\}', 'gi'); key = key.replace(reg,agrs[i]) }
The problem is that it’s not able to take the param i to create the reg exp.
What’s the way to achieve this?
Your regexp is
/{0}/gisince you create it from a string. And it is not a valid expression. You need to escape { in the regexp because it has a special meaning in the regexp syntax, so it should be:which is
/\\{0\\}/gi. You need to escape the escaping\\in the string.