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

时间:2016-04-08 08:16:39

标签: javascript html regex

我是正则表达式的新手,尝试过滤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>

问题是从锚标记中丢弃“样式”属性。 我试图使用*运算符,{3}选择器复制(\s(src|href|style)=['\"][^'\"]*['\"])块以及更多但是徒劳无功。 任何建议???

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

根据你原来的正则表达式,你去了:

set text=thisIsMyText
set file=file.txt
%text% > %file%

组1是标签名称,组2是属性,组3是<([a-z][a-z0-9]*?)(?:[^>]*?((?:\s(?:src|href|style)=['\"][^'\"]*['\"]){0,3}))[^>]*?(\/?)> (如果有)。我无法使用与允许的属性交错的非允许属性来处理它,例如/。我不认为可以做到。

编辑:Per @ AhmadAhsan在正则表达式下面的更正应该是:

<a href="foo" class="bar" src="baz" />
相关问题