How to pass a variable into regex in jQuery/Javascript

JqueryRegexMatch

Jquery Problem Overview


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:

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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncinematicView Question on Stackoverflow
Solution 1 - JqueryJonathan LonowskiView Answer on Stackoverflow
Solution 2 - Jqueryuser181548View Answer on Stackoverflow
Solution 3 - JqueryPurkhalo AlexView Answer on Stackoverflow
Solution 4 - JqueryMarllon DrionView Answer on Stackoverflow