How to pass a variable into regex in jQuery/Javascript How to pass a variable into regex in jQuery/Javascript jquery jquery

How to pass a variable into regex in jQuery/Javascript


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


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


It's easy, you need to create a RegExp instance with a variable.When I searched for the answer, I also wanted this string to being interpolated with regarding variable.

Try it out in a browser console:

let b = 'b';(new RegExp(`^a${b}c$`)).test('abc');// true