77

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?

Community
  • 1
  • 1
  • Duplicate of [How do you use a variable in a regular expression?](https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression) – Dan Dascalescu Jul 04 '17 at 11:35

4 Answers4

104

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));
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
43

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));
  • 2
    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. –  Nov 08 '09 at 07:31
  • 4
    I don't think you can apply regex options with this version (global, case-insensitive, for instance). I'd say @Jonathan's answer is more appropriate than this one. – nzifnab Feb 23 '13 at 19:00
  • 2
    It also only works with match. Other calls, like replace, require constructing the regex explicitly. – bronson Oct 19 '13 at 22:04
16

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:

const b = 'b';
const result = (new RegExp(`^a${b}c$`)).test('abc');

console.log(result);
Randy
  • 9,419
  • 5
  • 39
  • 56
Purkhalo Alex
  • 3,309
  • 29
  • 27
-7

Another way to include a variable in a string is through string interpolation. In JavaScript, you can insert or interpolate variables in strings using model literals:

var name = "Jack";
var id = 123321;

console.log(`Hello, ${name} your id is ${id}.`);

Note: be careful not to confuse quotation marks or apostrophes for the serious accent (`).

You can use in function:

function myPhrase(name, id){
   return `Hello, ${name} your id is ${id}.`;
}