繁体   English   中英

正则表达式从嵌套的 html 标签中删除所有属性 - Javascript

[英]Regex to remove all attributes from nested html tags - Javascript

我想使用正则表达式删除 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&ouml;&nbsp;
    <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 class="abc"> Test text</p></span>

由于安全原因,需要删除属性

我试图删除的内容

s/(<\w+)\s+[^>]*/$1/

<*\b[^<]*>(?:[^<]+(?:<(?!\/?div\b)[^<]*)*|(?R))*<\/*>\s*
<([a-z][a-z0-9]*)[^>]*?(\/?)>

但不工作

不应该使用正则表达式来解析 HTML。

相反,您应该使用DOMParser来解析字符串,遍历每个元素的属性并使用Element.removeAttribute

 const str = `<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&ouml;&nbsp; <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))

我建议你不要在这种情况下使用正则表达式,但如果你别无选择,也许你正在寻找这样的东西:

/<\s*([a-z][a-z0-9]*)\s.*?>/gi 

使用 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&ouml;&nbsp; <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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM