使用正则表达式从html获取类名 [英] Regular expression to get a class name from html
本文介绍了使用正则表达式从html获取类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I know my question might look like a duplication for this question, but its not
I am trying to match a class name inside html text that comes from the server as a template using JavsScript RegExp and replace it with another class name.
here what the code looks like :
<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) -->
例如,我想将"b"类与尽可能高的性能匹配
I want to match the class "b" for example
with the highest performance possible
这是我使用的正则表达式,但并非在所有情况下都有效,我也不知道为什么:
here is a regular expression I used but it's not working in all cases, and I don't know why :
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
推荐答案
使用正则表达式,此模式应适用于您:
Using a regex, this pattern should work for you:
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. ]
例如
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
注意:
为了使上述正则表达式正常工作,类字符串中必须没有'
或"
.
IE.< div class ="a'b'c d" ...
将不匹配.
这篇关于使用正则表达式从html获取类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文