3

Is there a way to pass a variable into a regex in jQuery/Javascript?

I wanna do something like:

var variable_regex = "bar";
var some_string = "foobar";

some_string.match(/variable_regex/);

In Ruby you would be able to do:

some_string.match(/#{variable_regex}/)

Found a useful post:

http://stackoverflow.com/questions/185510/how-can-i-concatenate-regex-literals-in-javascript

flag

2 Answers

3

It's easy:

var variable_regex = "bar";
var some_string = "foobar";

some_string.match(variable_regex);

Just lose the //. If you want to use complex regexes, you can use string concatenation:

var variable_regex = "b.";
var some_string = "foobar";

alert (some_string.match("f.*"+variable_regex));
link|flag
I don't know why I didn't see this. Thanks. – cinematic Nov 8 '09 at 7:28
I had a complex regex and I wanted to interpolate a variable pattern into a hardcoded expression, but I guess I'd just set each regex permutation to a whole variable. – cinematic Nov 8 '09 at 7:31
2

Javascript doesn't support interpolation like Ruby -- you have to use the RegExp constructor:

var aString = "foobar";
var pattern = "bar";

var matches = aString.match(new RegExp(pattern));
link|flag
Thanks, this is what I was looking for. – cinematic Nov 8 '09 at 7:25

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.