有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
对公认答案的改进。
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请求。
其他回答
我自己创建了一个工作正则表达式:
str=str.replace(/(<\?[a-z]*(\s[^>]*)?\?(>|$)|<!\[[a-z]*\[|\]\]>|<!DOCTYPE[^>]*?(>|$)|<!--[\s\S]*?(-->|$)|<[a-z?!\/]([a-z0-9_:.])*(\s[^>]*)?(>|$))/gi, '');
输入元素仅支持单行文本:
文本状态表示元素值的单行纯文本编辑控件。
function stripHtml(str) {
var tmp = document.createElement('input');
tmp.value = str;
return tmp.value;
}
更新:这是预期的
function stripHtml(str) {
// Remove some tags
str = str.replace(/<[^>]+>/gim, '');
// Remove BB code
str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2 ');
// Remove html and line breaks
const div = document.createElement('div');
div.innerHTML = str;
const input = document.createElement('input');
input.value = div.textContent || div.innerText || '';
return input.value;
}
myString.replace(/<[^>]*>?/gm, '');
还可以使用出色的htmlparser2纯JSHTML解析器。这里是一个工作演示:
var htmlparser = require('htmlparser2');
var body = '<p><div>This is </div>a <span>simple </span> <img src="test"></img>example.</p>';
var result = [];
var parser = new htmlparser.Parser({
ontext: function(text){
result.push(text);
}
}, {decodeEntities: true});
parser.write(body);
parser.end();
result.join('');
输出将是这是一个简单的示例。
请在此处查看实际操作:https://tonicdev.com/jfahrenkrug/extract-text-from-html
如果您使用类似webpack的工具打包web应用程序,则这在节点和浏览器中都有效。
用jQuery剥离html的一种更安全的方法是,首先使用jQuery.parseHTML创建DOM,忽略任何脚本,然后让jQuery构建元素,然后仅检索文本。
function stripHtml(unsafe) {
return $($.parseHTML(unsafe)).text();
}
可以安全地从以下位置剥离html:
<img src="unknown.gif" onerror="console.log('running injections');">
以及其他漏洞。
nJoy!