fre*_*ent 2 javascript regex variables
我在sinon.js fakeServer响应中使用以下作为regex pattnern :
/https:\/\/ca-davstorage:8080\/myFile.json(\?.*|$)/
Run Code Online (Sandbox Code Playgroud)
我想myFile
用变量替换,但由于我不是很擅长正则表达式,所以我很难让它发挥作用.目前我有这个,但似乎没有用.
'https:\\/\\/ca-davstorage:8080\\/'+myFile+'.json(\\?.*|$)/'
Run Code Online (Sandbox Code Playgroud)
问题:
如何正确地将变量添加到正则表达式?
感谢帮助!
而不是/regex/
使用构造函数RegExp
.
示例:
var foo = 'bar',
re = new RegExp('[0-9]' + foo, 'g');
re.test('1bar'); //true
Run Code Online (Sandbox Code Playgroud)
RegExp构造函数的第一个参数是正则表达式,第二个参数是修饰符.