Eva*_*que 5 javascript regex performance
我知道我的问题可能看起来像这个问题的重复,但它不是
我试图匹配来自服务器的html 文本中的类名作为模板使用 JavsScript RegExp 并将其替换为另一个类名。代码如下:
<div class='a b c d'></div>
<!-- or -->
<div class="a b c d"></div>
<!-- There might be spaces after and before the = (the equal sign) -->
Run Code Online (Sandbox Code Playgroud)
例如,我想将“b”类
与可能的最高性能相匹配
这是我使用的正则表达式,但它不适用于所有情况,我不知道为什么:
var key = 'b';
statRegex = new RegExp('(<[\w+ class="[\\w\\s]*?)\\b('+key+')\\b([\\w\\s]*")');
html.replace( statRegex,'SomeOtherClass');// I may be mistake by the way I am replacing it here
Run Code Online (Sandbox Code Playgroud)
使用正则表达式,这种模式应该适合你:
var r = new RegExp("(<\\w+?\\s+?class\\s*=\\s*['\"][^'\"]*?\\b)" + key + "\\b", "i");
# ? ? ?
# |_________________________________________| |
# ____________| |
# [Creating a backreference] |
# [which will be accessible] [Using "i" makes the matching "case-insensitive".]_|
# [using $1 (see examples).] [You can omit "i" for case-sensitive matching. ]
Run Code Online (Sandbox Code Playgroud)
例如
var oldClass = "b";
var newClass = "e";
var r = new RegExp("..." + oldClass + "...");
"<div class='a b c d'></div>".replace(r, "$1" + newClass);
// ^-- returns: <div class='a e c d'></div>
"<div class=\"a b c d\"></div>".replace(r, "$1" + newClass);
// ^-- returns: <div class="a e c d"></div>
"<div class='abcd'></div>".replace(r, "$1" + newClass);
// ^-- returns: <div class='abcd'></div> // <-- NO change
Run Code Online (Sandbox Code Playgroud)
注意:
要使上述正则表达式起作用,类字符串中必须没有'或"在。
即<div class="a 'b' c d"...会不匹配。
| 归档时间: |
|
| 查看次数: |
10499 次 |
| 最近记录: |