我有以下html代码:<div data-123 style="background-color: green; color: red;">
<div style="background-color: green;">Hello World <p>Another tag</p></div>
</div>我正在尝试匹配我使用此正则表达式的样式属性:/(style=)("|')(\w.+)("|')/i我只想匹配第一行,即如果第一行/标签中没有样式标签,那么它不应该匹配样式标签的下一行。我尝试了以下方法,但它不起作用:/\A.*(style=)("|')(\w.+)("|')/i
2 回答
猛跑小猪
TA贡献1858条经验 获得超8个赞
不要使用 RegEx 从 string 中提取属性/元素。
您可以使用 DOM API 来提取属性值。
const str = `<div data-123 style="background-color: green; color: red;">
<div style="background-color: green;">Hello World <p>Another tag</p></div>
</div>`;
const el = document.createElement('div');
el.innerHTML = str;
const div = el.querySelector('div[data-123]');
console.log(div.getAttribute('style'));
慕桂英4014372
TA贡献1871条经验 获得超13个赞
我认为您的问题是由于正则表达式匹配的贪婪行为。尝试将正则表达式转换为非贪婪匹配。请检查https://javascript.info/regexp-greedy-and-lazy
添加回答
举报
0/150
提交
取消
