Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex pattern concatenate with variable

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

like image 461
Komang Avatar asked Apr 26 '10 11:04

Komang


People also ask

Can you concatenate regex?

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.

Can you use variable in regex Javascript?

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 I create a dynamic expression in regex?

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.


2 Answers

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

like image 62
bobince Avatar answered Sep 20 '22 11:09

bobince


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))
like image 42
J.G.Sebring Avatar answered Sep 20 '22 11:09

J.G.Sebring