Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable into regex in jQuery/Javascript

People also ask

Can I use a variable in regex JS?

Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .

How do you add a variable in regex?

%s symbol to put a variable in regex pattern We can also use the %s symbol to put a variable in the regex pattern.

What is G in regex?

The g flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ( g ) and sticky ( y ) will ignore the global flag and perform sticky matches.

What are regex patterns?

A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.


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:

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

console.log(result);