How to pass a variable into regex in jQuery/Javascript

cinematic picture cinematic · Nov 8, 2009 · Viewed 46.7k times · Source

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:

How can I concatenate regex literals in JavaScript?

Answer

Jonathan Lonowski picture Jonathan Lonowski · Nov 8, 2009

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));