一个正则表达式,用于从JS中的HTML标记中删除id,style,class属性 [英] A regex to remove id, style, class attributes from HTML tags in JS
本文介绍了一个正则表达式,用于从JS中的HTML标记中删除id,style,class属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在javascript中有一个html字符串,并使用正则表达式,想删除html标记中的id,style和class属性,例如,我有:
I got a html String in javascript and using regex I want to remove id, style and class attributes in html tags, for example I have:
New York City.<div style="padding:20px" id="upp" class="upper"><div style="background:#F2F2F2; color:black; font-size:90%; padding:10px 10px; width:500px;">This message is.</div></div>
我希望此字符串成为:
New York City.<div><div>This message is.</div></div>
推荐答案
Instead of parsing the HTML using regular expressions, which is a bad idea, you could take advantage of the DOM functionality that is available in all browsers. We need to be able to walk the DOM tree first:
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
walk(node, func);
node = node.nextSibling;
}
};
现在解析字符串并处理DOM:
Now parse the string and manipulate the DOM:
var wrapper= document.createElement('div');
wrapper.innerHTML= '<!-- your HTML here -->';
walk_the_DOM(wrapper.firstChild, function(element) {
if(element.removeAttribute) {
element.removeAttribute('id');
element.removeAttribute('style');
element.removeAttribute('class');
}
});
result = wrapper.innerHTML;
另请参见此JSFiddle .
这篇关于一个正则表达式,用于从JS中的HTML标记中删除id,style,class属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文