我是新手到正則表達式,嘗試過濾HTML標記,只保留它們的值所需的(src/href/style)屬性並刪除不必要的屬性。雖然谷歌上搜索,我發現一個正則表達式只保留「src」屬性,因此我的修飾表達如下:使用JavaScript從html標記中刪除不必要的屬性正則表達式
<([a-z][a-z0-9]*)(?:[^>]*(\s(src|href|style)=['\"][^'\"]*['\"]))?[^>]*?(\/?)>
其工作正常,但唯一的問題是,如果一個標籤包含一個以上的所需屬性,那麼它只保留最後匹配的單個屬性並丟棄其餘的。
我試圖清理在https://regex101.com/#javascript以下文本
<title>Hello World</title>
<div fadeout"="" style="margin:0px;" class="xyz">
<img src="abc.jpg" alt="" />
<p style="margin-bottom:10px;">
The event is celebrating its 50th anniversary Kö
<a style="margin:0px;" href="http://www.germany.travel/">exhibition grounds in Cologne</a>.
</p>
<p style="padding:0px;"></p>
<p style="color:black;">
<strong>A festival for art lovers</strong>
</p>
</div>
使用上述表達<$1$2$4>
作爲替換字符串並獲得以下輸出:
<title>Hello World</title>
<div style="margin:0px;">
<img src="abc.jpg"/>
<p style="margin-bottom:10px;">
The event is celebrating its 50th anniversary Kö
<a href="http://www.germany.travel/">exhibition grounds in Cologne</a>.
</p>
<p style="padding:0px;"></p>
<p style="color:black;">
<strong>A festival for art lovers</strong>
</p>
</div>
問題是「風格」屬性是從廢棄錨標籤。 我試圖複製(\s(src|href|style)=['\"][^'\"]*['\"])
塊使用*運算符,{3}選擇器和更多,但徒勞無功。 任何建議???
我可以建議使用使用RegexBuddy測試表達式。這爲我節省了很多時間。 https://www.regexbuddy.com/ –
有關OP的代碼,請參考https://regex101.com/r/mP0pX6/1 –
爲什麼不使用DOM操作而不是RegEX? –