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() .
%s symbol to put a variable in regex pattern We can also use the %s symbol to put a variable in the regex pattern.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With