javascript
js 动态拼接html 正则,在JavaScript中使用动态(可变)字符串作为正则表达式模式...
小編典典
要從字符串創(chuàng)建正則表達(dá)式,必須使用JavaScript的RegExpobject。
如果你也想匹配/替換超過一次,那么你就 必須添加的g(全局匹配)標(biāo)志。這是一個例子:
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.
在一般情況下,在用作正則表達(dá)式前先對字符串進(jìn)行轉(zhuǎn)義:
但是,并非每個字符串都是有效的正則表達(dá)式:有些特殊字符,例如(或[。要變通解決此問題,只需將字符串轉(zhuǎn)為正則表達(dá)式之前先對其進(jìn)行轉(zhuǎn)義。下面的示例中包含一個實用程序功能:
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.
注意:問題中的正則表達(dá)式使用s修飾符,該修飾符在提問時并不存在 ,但今天確實存在 -JavaScript中 的s( dotall)標(biāo)志/修飾符。
2020-05-01
總結(jié)
以上是生活随笔為你收集整理的js 动态拼接html 正则,在JavaScript中使用动态(可变)字符串作为正则表达式模式...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 奥迪a62.8高压线怎么插
- 下一篇: gradle idea java ssm