飲歌長嘯
2022-01-07 19:26:45
我有以下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我只想匹配第一行,即如果第一行/標簽中沒有樣式標簽,那么它不應(yīng)該匹配樣式標簽的下一行。我嘗試了以下方法,但它不起作用:/\A.*(style=)("|')(\w.+)("|')/i
2 回答

猛跑小豬
TA貢獻1858條經(jīng)驗 獲得超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條經(jīng)驗 獲得超13個贊
我認為您的問題是由于正則表達式匹配的貪婪行為。嘗試將正則表達式轉(zhuǎn)換為非貪婪匹配。請檢查https://javascript.info/regexp-greedy-and-lazy
添加回答
舉報
0/150
提交
取消