有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
下面的代码允许您保留一些html标记,同时剥离所有其他标记
function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
其他回答
使用Jquery:
function stripTags() {
return $('<p></p>').html(textToEscape).text()
}
对公认答案的改进。
function strip(html)
{
var tmp = document.implementation.createHTMLDocument("New").body;
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
这样一来,像这样运行的东西不会造成任何伤害:
strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")
Firefox、Chromium和Explorer 9+是安全的。歌剧院普雷斯托仍然很脆弱。字符串中提到的图像也不会在Chromium和Firefox中保存http请求。
我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:
stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");
在尝试了所有提到的答案后,如果不是所有答案都有边缘案例,也不能完全支持我的需求。
我开始探索php是如何做到这一点的,并在这里遇到了复制strip_tags方法的php.js库:http://phpjs.org/functions/strip_tags/
(function($){
$.html2text = function(html) {
if($('#scratch_pad').length === 0) {
$('<div id="lh_scratch"></div>').appendTo('body');
}
return $('#scratch_pad').html(html).text();
};
})(jQuery);
将其定义为jquery插件,并按如下方式使用:
$.html2text(htmlContent);