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

Answers:

Answer

With ES5 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))
// prints array of ['53']
Answer
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.)

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.