Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing variable to a regexp in javascript [duplicate]

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?

like image 985
Nrj Avatar asked Jan 28 '09 12:01

Nrj


People also ask

How do you pass a variable in regex?

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.

Can you put a variable inside a regex?

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.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How do you clone a regular expression in JavaScript?

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.


1 Answers

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.

like image 92
artificialidiot Avatar answered Sep 20 '22 12:09

artificialidiot