Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从html获取类名的正则表达式_Javascript_Regex_Performance - Fatal编程技术网

Javascript 从html获取类名的正则表达式

Javascript 从html获取类名的正则表达式,javascript,regex,performance,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 = (t

我知道我的问题看起来像是重复的,但事实并非如此
我试图在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) -->

例如,我想将“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
var键='b';

statRegex=new RegExp(“(这可能不是您的解决方案,但是如果您没有使用完整的regex匹配,您可以这样做(假设您的示例代表您将要分析的数据) :

函数有类(html\u字符串,类名){
//!!~将-1变为假,将其他任何内容变为真。
return!!~html\u string.split(“=”[1]。split(/[\'\“]/)[1]。split(“”)。indexOf(classname);
}
hasTheClass(“,'b');//返回true

使用正则表达式,此模式适用于您:

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 r=new RegExp((正则表达式不适合解析HTML。HTML不是正则表达式

jQuery非常适合这里

var html = 'Your HTML here...';

$('<div>' + html + '</div>').find('[class~="b"]').each(function () {
    console.log(this);
});
var html='Your html here…';
$(''+html+'').find('[class~=“b”]')。each(函数(){
console.log(this);
});

选择器
[class~=“b”]
将选择具有
class
属性且包含单词
b
的任何元素。初始HTML包装在
div
中,以使
find
方法正常工作。

请使用浏览器:

var str = '<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) -->';

var wrapper = document.createElement('div');
wrapper.innerHTML = str;

var elements = wrapper.getElementsByClassName('b');

if (elements.length) {
    // there are elements with class b
}
var-str='\
\
\
';
var wrapper=document.createElement('div');
wrapper.innerHTML=str;
var elements=wrapper.getElementsByClassName('b');
if(元素长度){
//有b类元素
}

顺便说一句,
getElementsByClassName()
直到第9版才在IE中得到很好的支持;请检查替代方案。

在此处测试:

regexp:
(?:class | className)=(?:[“']\W+\s*(?:\W+\())([“'])([^']+)[“]

const regex=/(?:class | className)=(?:[“]\W+\s*(?:\W+\()?[”])([^']+)[“]/gmi;
常量str=`
`;
让m;
while((m=regex.exec(str))!==null){
//这是避免具有零宽度匹配的无限循环所必需的
if(m.index==regex.lastIndex){
regex.lastIndex++;
}
//可以通过'm`-变量访问结果。
m、 forEach((匹配,组索引)=>{
log(`Found match,group${groupIndex}:${match}`);
});

}
我知道这并不比dom操作快,但我从服务器获取的文本不是dom,我正在使用一个特殊的框架将HTML转换为dom元素很容易;-)@AymanJitan您不知道HTML不是正则的,因此不适合正则表达式。请参阅。使用DOM显然是最好的方法。@Bart我有小部件,每个小部件都由许多HTML模板组成,每个小部件内都有具有不同状态的组件,状态由css类控制,我需要解析html并在不同的状态下显示组件和小部件。这很难解释。我知道dom要快得多,但它在我的环境中无法工作case@AymanJitan我可以想象这很复杂,但你没有抓住我想说的重点。这不是速度的问题,而是现在和将来得到正确的结果未来。当HTML格式发生变化时,正则表达式很可能会失败,因为DOM将为您提供可靠的结果。这种过度使用拆分方式将花费大量时间+1个很好的时间。唯一的缺点是IE<9不支持
getElementsByClassName
@Bart不支持什么?哦,你是说
getElementsByClassName
?这可能是一个完美的解决方案,但对我来说不是。在将html注入页面之前,我正在对html进行一些更改,dom对我使用的框架没有帮助。@AymanJitan所以在dom中进行更改?不太清楚框架是如何阻止您这样做的。@AymanJitan进行更改并获取
包装器.innerHTML
。没有比这更简单的了。谢谢,但我不使用jQuery,也不愿意使用dom操作这是一个全新的问题:)请编辑您的问题,明确说明您想要实现的目标(我将更新我的答案)。很抱歉,但此正则表达式匹配整个元素,我只在匹配类之后
var html = 'Your HTML here...';

$('<div>' + html + '</div>').find('[class~="b"]').each(function () {
    console.log(this);
});
var str = '<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) -->';

var wrapper = document.createElement('div');
wrapper.innerHTML = str;

var elements = wrapper.getElementsByClassName('b');

if (elements.length) {
    // there are elements with class b
}