Komang
Komang

Reputation: 5064

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

Upvotes: 123

Views: 109459

Answers (3)

J.G.Sebring
J.G.Sebring

Reputation: 5964

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

Upvotes: 29

Lauri
Lauri

Reputation: 1303

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

Upvotes: 8

bobince
bobince

Reputation: 536339

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

Upvotes: 184

Related Questions