我有一个简单的正则表达式:
str.match(/SK=([\w\-]+)/i);
我希望 SK
部分是动态的,这样我就可以返回 SK=
、WP=
等的匹配...
所以我正在寻找类似的东西:
var attr = 'SK';
str.match(/' + attr + '=([\w\-]+)/i);
最佳答案
使用构造函数语法创建正则表达式:
var myRegex = new RegExp(attr + "([\\w\\-]+)","i");
然后:
str.match(myRegex);
请参阅此处(强调我的):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
关于javascript - 动态变量写入正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22388821/