我将以下元素存储为字符串:
<div class="some-class" id="my-id" data-theme="black">
<strong data-animation="fade" disabled>Hello world!</strong>
</div>
我想像这样提取所有属性名称:
["class", "id", "data-theme", "data-animation", "disabled"]
这是我尝试做的,但我也得到了与数据动画和禁用相匹配的值和剂量:
http://jsbin.com/hibebezibo/edit?js,console
编辑:
管理获取属性使用:
[\w-]+(?=\s*=\s*".*?")
但我仍然无法获得“禁用” Prop 。
有人可以向我解释如何实现这一目标吗? 谢谢!
最佳答案
使用下面的正则表达式可以匹配属性的名称:
[ ][\w-]+(?=[^<]*>)
注意:在字符类中添加-
是必须的。
javascript代码:
const HtmlElement = `<div class="some-class" id="my-id" data-theme="black">
<strong data-animation="fade" disabled>Hello world!</strong>
</div>`
console.log(HtmlElement.match(/ [\w-]+(?=[^<]*>)/g).map(function(element) {
return element.trimLeft();
}));
但是它不是万能的,因为它可以匹配 > 之后的单词
。例如:
<strong data-animation="fade" disabled>Hello world!></strong>
因此建议使用 DOM 功能来完成这样的任务:
var html = document.createElement('div');
html.innerHTML = '<div class="some-class" id="my-id" xlink:href data-theme="black"><strong data-animation="fade" disabled>Hello world!</strong></div>';
var attrNodes = document.evaluate('//*/attribute::*', html, null, XPathResult.ANY_TYPE, null)
var nextAttrNode = attrNodes.iterateNext()
var arrAttrs = [];
while (nextAttrNode) {
arrAttrs.push(nextAttrNode.name)
nextAttrNode = attrNodes.iterateNext();
}
console.log(arrAttrs)
关于javascript - 正则表达式匹配 HTML 属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43272352/