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?
If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() . In the above code, we have passed the removeStr variable as an argument to the new RegExp() constructor method.
It's not reeeeeally a thing. There is the regex constructor which takes a string, so you can build your regex string which includes variables and then pass it to the Regex cosntructor.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
We can clone a given regular expression using the constructor RegExp(). Here regExp is the expression to be cloned and flags determine the flags of the clone. There are mainly three types of flags that are used. g:global flag with this flag the search looks for global match.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With