How to pass a variable into regex in jQuery/Javascript

Viewed 61804

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?

4 Answers

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

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}.`;
}
Related