JavaScript regex pattern concatenate with variable

JavascriptRegex

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKomangView Question on Stackoverflow
Solution 1 - JavascriptbobinceView Answer on Stackoverflow
Solution 2 - JavascriptJ.G.SebringView Answer on Stackoverflow
Solution 3 - JavascriptLauriView Answer on Stackoverflow