views:

46

answers:

3

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?

+1  A: 

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.

Mark Biek
Remove the delimiters and it’s fine.
Gumbo
Whoops, thanks!
Mark Biek
+2  A: 

You can use the new RegExp method:

var resource = "user";
new RegExp("^\/"+variable+"\/\d+$");
Christian
+3  A: 

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+$");
Gumbo