gpt4 book ai didi

javascript - 使用 JavaScript RegEx 从 html 标签中删除不必要的属性

转载 作者:搜寻专家 更新时间:2023-10-31 22:58:27 25 4
gpt4 key购买 nike

我是正则表达式的新手,试图过滤 HTML 标签,只保留必需的 (src/href/style) 属性及其值,并删除不必要的属性。在谷歌搜索时我发现了一个正则表达式只保留“src”属性,因此我修改后的表达式如下:

<([a-z][a-z0-9]*)(?:[^>]*(\s(src|href|style)=['\"][^'\"]*['\"]))?[^>]*?(\/?)>

它工作正常,但唯一的问题是,如果一个标签包含多个必需属性,那么它只保留最后一个匹配的单个属性并丢弃其余属性。

我正在尝试清理以下文本

<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&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>

https://regex101.com/#javascript将上述表达式与 <$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&ouml;&nbsp;
<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>

问题是“样式”属性从 anchor 标记中被丢弃。我试图复制 (\s(src|href|style)=['\"][^'\"]*['\"])阻止使用 * 运算符、{3} 选择器等等,但都是徒劳的。有什么建议吗???

最佳答案

@AhmadAhsan 这是使用 DOM 操作解决问题的演示:https://jsfiddle.net/pu1hsdgn/

   <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script>
var whitelist = ["src", "href", "style"];
$( document ).ready(function() {
function foo(contents) {
var temp = document.createElement('div');
var html = $.parseHTML(contents);
temp = $(temp).html(contents);

$(temp).find('*').each(function (j) {
var attributes = this.attributes;
var i = attributes.length;
while( i-- ) {
var attr = attributes[i];
if( $.inArray(attr.name,whitelist) == -1 )
this.removeAttributeNode(attr);
}
});
return $(temp).html();
}
var raw = '<title>Hello World</title><div style="margin:0px;" fadeout"="" class="xyz"><img src="abc.jpg" alt="" /><p style="margin-bottom:10px;">The event is celebrating its 50th anniversary K&ouml;&nbsp;<a href="http://www.germany.travel/" style="margin:0px;">exhibition grounds in Cologne</a>.</p><p style="padding:0px;"></p><p style="color:black;"><strong>A festival for art lovers</strong></p></div>'
alert(foo(raw));
});
</script>

关于javascript - 使用 JavaScript RegEx 从 html 标签中删除不必要的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36494743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com