如何删除除特定标记之外的所有标记属性?

时间:2017-01-29 16:42:27

标签: javascript jquery html regex

我有这个字符串:

var str = '<p>paragraph<a>link</a></p>
           <div class="myclass">
               <div>something</div>
               <div style="mystyle">something</div>
               <b><a href="#">link</a></b>
               <b><a href="#" name="a name">link</a></b>
               <b style="color:red">bold</b>
               <img src="../path" alt="something" />
               <img src="../path" alt="something" class="myclass" />
           </div>';

我想删除除hrefsrcalt以外的所有属性。所以这是预期的结果:

/* 
<p>paragraph<a>link</a></p>
<div>
    <div>something</div>
    <div>something</div>
    <b><a href="#">link</a></b>
    <b><a href="#">link</a></b>
    <b>bold</b>
    <img src="../path" alt="something">
    <img src="../path" alt="something">
</div>

我该怎么做?

我可以选择它们并非有用:

/<[a-z]+ .*?(href|src|alt)="[^"]+"/g

2 个答案:

答案 0 :(得分:3)

var str = `<p>paragraph<a>link</a></p>
           <div class="myclass">
               <div>something</div>
               <div style="mystyle">something</div>
               <b><a href="#">link</a></b>
               <b><a href="#" name="a name">link</a></b>
               <b style="color:red">bold</b>
               <img src="../path" alt="something" />
               <img src="../path" alt="something" class="myclass" />
           </div>`;
var div = document.createElement("div");
div.innerHTML=str;
div.querySelectorAll("*").forEach(function(el){
  for (var i = 0, atts = el.attributes, n = atts.length; i < n; i++){
    var att = atts[i].nodeName;
    if (["src","alt","href"].indexOf(att) ==-1) el.removeAttribute(att); 
  }
}); 
// console.log(div); alert shows it more clearly
alert(div.innerHTML);

PS:请注意,您需要使用反引号引用带有嵌入换行符的字符串

答案 1 :(得分:1)

var str = `<p>paragraph<a>link</a></p>
           <div class="myclass">
               <div>something</div>
               <div style="mystyle">something</div>
               <b><a href="#">link</a></b>
               <b><a href="#" name="a name">link</a></b>
               <b style="color:red">bold</b>
               <img src="../path" alt="something" />
               <img src="../path" alt="something" class="myclass" />
           </div>`;
var $div =$("<div>");
$div.html(str);
  $div.find("*").each(function() {

    var attributes = $.map(this.attributes, function(item) {
      return item.name;
    });

    // now use jQuery to remove the attributes
    var element = $(this);
    $.each(attributes, function(i, item) {
      if (["href", "src", "alt"].indexOf(item) == -1)
        element.removeAttr(item);
    });


  });
console.log($div.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>