在 JavaScript 中使用动态(可变)字符串作为正则表达式模式

新手上路,请多包涵

我想使用正则表达式向值 添加一个(变量)标签,该模式适用于 PHP,但我在将其实现到 JavaScript 中时遇到了麻烦。

模式是( value 是变量):

/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is

我逃脱了反斜杠:

var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "<a href='#" + value +">" + value + "</a>"));

但这似乎不对,我记录了模式及其应该是什么。

有任何想法吗?

原文由 Borstenhorst 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 893
2 个回答

要从字符串创建正则表达式,您必须使用 JavaScript 的 RegExp 对象

如果您还想多次匹配/替换,则 必须 添加 g (全局匹配)标志。这是一个例子:

 var stringToGoIntoTheRegex = "abc";
 var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
 // at this point, the line above is the same as: var regex = /#abc#/g;

 var input = "Hello this is #abc# some #abc# stuff.";
 var output = input.replace(regex, "!!");
 alert(output); // Hello this is !! some !! stuff.

JSFiddle 演示在这里。

在一般情况下,在用作正则表达式之前转义字符串:

但是,并非每个字符串都是有效的正则表达式:有一些特殊字符,例如 ([ 。要解决此问题,只需在将字符串转换为正则表达式之前将其转义即可。下面的示例中有一个实用函数:

 function escapeRegExp(stringToGoIntoTheRegex) {
 return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
 }

 var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
 var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
 // at this point, the line above is the same as: var regex = /#abc#/g;

 var input = "Hello this is #abc# some #abc# stuff.";
 var output = input.replace(regex, "!!");
 alert(output); // Hello this is !! some !! stuff.

JSFiddle 演示在这里。


注意:问题中的正则表达式使用 s 修饰符,该修饰符在提出问题时不存在, 确实存在- JavaScript 中的 s ( dotall ) 标志/修饰符 - today

原文由 acdcjunior 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您试图在表达式中使用变量值,则必须使用 RegExp“构造函数”。

 var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")

原文由 mothmonsterman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题