How to create regex pattern which is concatenate with variable, something like this:
var test ="52"; var re = new RegExp("/\b"+test+"\b/"); alert('51,52,53'.match(re));
Thanks
The Concatenation OperatorThis operator concatenates two regular expressions a and b . No character represents this operator; you simply put b after a . The result is a regular expression that will match a string if a matches its first part and b matches the rest.
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() .
To use dynamic variable string as regex pattern in JavaScript, we can use the RegExp constructor. const stringToGoIntoTheRegex = "abc"; const regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g"); to create a regex object by calling the RegExp constructor with the "#" + stringToGoIntoTheRegex + "#" string.
var re = new RegExp("/\b"+test+"\b/");
\b
in a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:
var re = new RegExp("\\b"+test+"\\b");
(You also don't need the //
in this context.)
With ES2015 (aka ES6) you can use template literals when constructing RegExp:
let test = '53' const regexp = new RegExp(`\\b${test}\\b`, 'gi') // showing how to pass optional flags console.log('51, 52, 53, 54'.match(regexp))
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