Possible Duplicate:
passing variable to a regexp in javascript
I have a variable:
resource = "user";
I want to insert that variable into a predefined RegExp (replacing variable beneath):
/^\/variable\/\d+$/
How could I do that?
Possible Duplicate:
passing variable to a regexp in javascript
I have a variable:
resource = "user";
I want to insert that variable into a predefined RegExp (replacing variable beneath):
/^\/variable\/\d+$/
How could I do that?
You should be able to do this.
var resource = "user";
var regex = new RegExp("^\/"+resource+"\/\d+$", "g");
You can then pass the RegExp object to functions like myString.replace()
or call the exec()
method of the RegExp object itself.
You can use the new RegExp
method:
var resource = "user";
new RegExp("^\/"+variable+"\/\d+$");
Use the constructor of RegExp
:
var re = new RegExp("^\\/" + resource + "\\/\\d+$");
Note that you need to escape the delimiters /
twice, once for the regular expression and once for the string declaration.
You also might want to use some escape function to quote strings to be used in regular expressions:
function quote(str) {
return str.replace(/(?=[\/\\^$*+?.()|{}[\]])/g, "\\");
}
That leads us to this:
var re = new RegExp("^\\/" + quote(resource) + "\\/\\d+$");