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

标签 javascript regex string

我想使用正则表达式向值添加(变量)标签,该模式在 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.

JSFiddle demo here.


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

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

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 demo here.



注意:问题中的正则表达式使用了 s 修饰符,该修饰符在问题出现时不存在,but does exist -- a s (dotall) flag/modifier in JavaScript -- today .

关于javascript - 在 JavaScript 中使用动态(可变)字符串作为正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17885855/

相关文章:

javascript - 为什么 obj.a = ( obj.a || [] ).push( 10 ) 使 obj.a 成为类型编号

regex - 替换正则表达式中的换行符

linux - 比较字符串时出现问题 (BASH)

python - if substring in string,当子串有多个值时

Python-从csv文件中消除正则表达式匹配

asp.net - 如何更改 ASP.NET 配置工具连接字符串

javascript - 取钱有困难吗?

javascript - 如何检查页面是否存在垂直滚动条?

javascript - Hello World 不能在带有 jointjs 的 html 中正常工作?

php - mysql 替换文本