JavaScript 正则表达式模式与变量连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2712878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:35:33  来源:igfitidea点击:

JavaScript regex pattern concatenate with variable

javascriptregex

提问by Komang

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

谢谢

回答by bobince

var re = new RegExp("/\b"+test+"\b/"); 

\bin a string literal is a backspace character. When putting a regex in a string literal you need one more round of escaping:

\b在字符串文字中是一个退格字符。将正则表达式放入字符串文字时,您需要再进行一轮转义:

var re = new RegExp("\b"+test+"\b"); 

(You also don't need the //in this context.)

//在这种情况下您也不需要。)

回答by Lauri

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

回答by Tapirboy

With ES2015 (aka ES6) you can use template literalswhen constructing RegExp:

使用 ES2015(又名 ES6),您可以在构造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']