Javascript – passing variable to a regexp in javascript


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?

Best Solution

Your regexp is /{0}/gi since 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:

new RegExp('\\{'+i+'\\}', 'gi');

which is /\\{0\\}/gi. You need to escape the escaping \\ in the string.