我想使用正則運算式洗掉 html 標簽的屬性。它可以是任何 html 元素并允許嵌套元素,例如:
<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>
或者它可能像
<span style="margin: 0;"><p > Test text</p></span>
由于安全原因,需要洗掉屬性
我試圖洗掉的內容
s/(<\w )\s [^>]*/$1/
<*\b[^<]*>(?:[^<] (?:<(?!\/?div\b)[^<]*)*|(?R))*<\/*>\s*
<([a-z][a-z0-9]*)[^>]*?(\/?)>
但不作業
uj5u.com熱心網友回復:
不應該使用正則運算式來決議 HTML。
相反,您應該使用 aDOMParser來決議字串,遍歷每個元素的屬性并使用Element.removeAttribute:
const str = `<div fadeout"="" style="margin:0px;" >
<img src="abc.jpg" alt="正則運算式從嵌套的 html 標簽中洗掉所有屬性 - Javascript" />
<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>`
function stripAttributes(html){
const parsed = new DOMParser().parseFromString(html, 'text/html')
parsed.body.querySelectorAll('*').forEach(elem => [...elem.attributes].forEach(attr => elem.removeAttribute(attr.name)))
return parsed.body.innerHTML;
}
console.log(stripAttributes(str))
uj5u.com熱心網友回復:
我建議你不要在這種情況下使用正則運算式,但如果你別無選擇,也許你正在尋找這樣的東西:
/<\s*([a-z][a-z0-9]*)\s.*?>/gi
uj5u.com熱心網友回復:
使用 DOM 的好處在于,您可以使用一整套專門用于操作 DOM 的工具!然而人們堅持認為這種復雜的結構化資料格式只是一個愚蠢的字串,并開始用正則運算式來破解它。
為作業使用正確的工具。
function removeAttributesRecursively(el) {
Array.from(el.attributes).forEach(function(attr) {
// you'll probably want to include extra logic here to
// preserve some attributes (a href, img src, etc)
// instead of blindly removing all of them
el.removeAttribute(attr.name);
});
// recurse:
Array.from(el.children).forEach(function(child) {
removeAttributesRecursively(child)
})
}
const root = document.getElementById('input');
removeAttributesRecursively(root)
console.log(root.innerHTML)
<div id="input">
<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>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354293.html
標籤:javascript html 正则表达式
