javascript - 动态变量写入正则表达式

标签 javascript regex

我有一个简单的正则表达式:

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/

相关文章:

php - 如何从字符串中删除所有数字?

javascript - 如果所有者是meteor js,则显示模板中的元素

java - 在字符串的任意位置出现一个字符的正则表达式

javascript - Google Maps API - 多个 map 的多个标记

javascript - 从字符串中返回一个单词

javascript - 如何通过改变 JavaScript 中的一个字符来置换字符串?

java - 使用 Java RegEx,如何将一个变量与另一个变量进行比较,同时忽略引号和空格?

Java - 正则表达式中字符类中的转义星

javascript - 如何在 jQuery 中创建无限循环?

javascript - 同步 Ajax 调用和executeQueryAsync Sh​​arePoint JS CSOM