我想使用正则表达式向值添加(变量)标签,该模式在 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>"));
但这似乎不对,我记录了模式,它应该是什么。 有什么想法吗?
最佳答案
要从字符串创建正则表达式,您必须使用 JavaScript's RegExp
object .
如果您还想匹配/替换不止一次,那么您必须添加the g
(global match) flag .这是一个例子:
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.
在一般情况下,在用作正则表达式之前对字符串进行转义:
但并非每个字符串都是有效的正则表达式:有一些特殊字符,如 (
或 [
。要解决此问题,只需在转义之前转义字符串它变成一个正则表达式。下面的示例中有一个实用函数:
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.
注意:问题中的正则表达式使用了 s
修饰符,该修饰符在问题出现时不存在,but does exist -- a s
(dotall) flag/modifier in JavaScript -- today .
关于javascript - 在 JavaScript 中使用动态(可变)字符串作为正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17885855/