120

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

informatik01
  • 16,038
  • 10
  • 74
  • 104
Komang
  • 5,004
  • 4
  • 29
  • 33

3 Answers3

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

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 16
    There are many places where the constructor-function of a built-in type may be used both with or without `new`. However, for consistency with other objects where this may not hold true, and clarity in general, I would always use `new`. – bobince Apr 26 '10 at 11:11
  • 1
    Another way is to use single-quotes for clarity so you don't need to escape the back-slashes: `new RegExp('\b'+test+'\b');` – IQAndreas Mar 14 '15 at 07:09
  • 6
    You still need to escape the backslashes. Single quotes don't have different escaping rules to double quotes in JavaScript (unlike, say, PHP). – bobince Mar 15 '15 at 09:40
  • This answer also solves the same question when trying to use the border-operators on a variable with the .match() and .replace() JS regexing functions. – HoldOffHunger Oct 25 '16 at 20:50
  • Just what I was looking for. The part about `When putting a regex in a string literal you need one more round of escaping`; is there any background information about (the reasons of) this? – Bas Peeters Jun 16 '17 at 12:28
  • CAn I use `body=body.replace('/'+reg+'/g', '')` instead of `new RegExp`? – Timo Mar 15 '21 at 20:37
  • @Timo No, your first argument is string not regex. – Saber Hayati Jul 15 '22 at 16:50
27

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))
double-beep
  • 5,031
  • 17
  • 33
  • 41
J.G.Sebring
  • 5,934
  • 1
  • 31
  • 42
8

you can use

/(^|,)52(,|$)/.test('51,52,53')

but i suggest to use

var list = '51,52,53';
function test2(list, test){
    return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )
Lauri
  • 1,298
  • 11
  • 13