使用javascript剥离标签(带有标签内部属性和嵌套标签)

时间:2013-11-08 09:18:37

标签: javascript strip-tags

从标签中剥离字符串的最快(性能)方式,大多数解决方案我试过使用regexp而不是为属性内的标签生成正确的值(是的,我知道它是错的),示例测试用例:

 var str = "<div data-content='yo! press this: <br/> <button type=\"button\"><i class=\"glyphicon glyphicon-disk\"></i> Save</button>' data-title='<div>this one for tooltips <div>seriously</div></div>'> this is the real content<div> with another nested</div></div>"

应该产生的结果:

 this is the real content with another nested

1 个答案:

答案 0 :(得分:3)

我认为使用innerText应该非常快:

var str = "<div data-content='yo! press this: <br/> <button type='button'><i class=\"glyphicon glyphicon-disk\"></i></button>' data-title='<div>this one for tooltips</div>'> this is the real content<div> with another nested</div></div>"; 
var el = document.createElement('div');
el.innerHTML = str;
var text = el.textContent || el.innerText;
alert(text);