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

Ahm*_*san 3 html javascript regex

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

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

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

我正在尝试清理以下文本

<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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

问题是“style”属性从锚标记中被丢弃。我尝试(\s(src|href|style)=['\"][^'\"]*['\"])使用 * 运算符、{3} 选择器等来复制该块,但徒劳无功。有什么建议么???

Ina*_*san 5

@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>
Run Code Online (Sandbox Code Playgroud)