700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > js 动态拼接html 正则 在JavaScript中使用动态(可变)字符串作为正则表达式模式...

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

时间:2020-04-11 23:05:59

相关推荐

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

小编典典

要从字符串创建正则表达式,必须使用JavaScript的RegExpobject。

如果你也想匹配/替换超过一次,那么你就 必须添加的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.

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

但是,并非每个字符串都是有效的正则表达式:有些特殊字符,例如(或[。要变通解决此问题,只需将字符串转为正则表达式之前先对其进行转义。下面的示例中包含一个实用程序功能:

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修饰符,该修饰符在提问时并不存在 ,但今天确实存在 -JavaScript中 的s( dotall)标志/修饰符。

-05-01

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。