如何创建与变量连接的正则表达式模式,如下所示:
var test ="52";
var re = new RegExp("/\b"+test+"\b/");
alert('51,52,53'.match(re));
Run Code Online (Sandbox Code Playgroud)
谢谢
bob*_*nce 128
var re = new RegExp("/\b"+test+"\b/");
Run Code Online (Sandbox Code Playgroud)
\b
在字符串文字中是退格字符.将正则表达式放在字符串文字中时,您需要再循环一次:
var re = new RegExp("\\b"+test+"\\b");
Run Code Online (Sandbox Code Playgroud)
(//
在这种情况下你也不需要.)
Tap*_*boy 15
使用 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))
Run Code Online (Sandbox Code Playgroud)
您可以使用
/(^|,)52(,|$)/.test('51,52,53')
Run Code Online (Sandbox Code Playgroud)
但我建议使用
var list = '51,52,53';
function test2(list, test){
return !((","+list+",").indexOf(","+test+",") === -1)
}
alert( test2(list,52) )
Run Code Online (Sandbox Code Playgroud)