我有这个字符串:
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>';
我想删除除
href
,src
,alt
之外的所有属性。所以这是预期的结果:/*
<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
最佳答案
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:请注意,您需要反引号来引用带有嵌入式换行符的字符串