JavaScript regex pattern concatenate with variable

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

Leave a Comment