有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
另一个公认不如nickf或Shog9优雅的解决方案是从<body>标记开始递归遍历DOM并附加每个文本节点。
var bodyContent = document.getElementsByTagName('body')[0];
var result = appendTextNodes(bodyContent);
function appendTextNodes(element) {
var text = '';
// Loop through the childNodes of the passed in element
for (var i = 0, len = element.childNodes.length; i < len; i++) {
// Get a reference to the current child
var node = element.childNodes[i];
// Append the node's value if it's a text node
if (node.nodeType == 3) {
text += node.nodeValue;
}
// Recurse through the node's children, if there are any
if (node.childNodes.length > 0) {
appendTextNodes(node);
}
}
// Return the final result
return text;
}
其他回答
function strip_html_tags(str)
{
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace(/<[^>]*>/g, '');
}
使用jQuery,您可以使用
$('#elementID').text()
输入元素仅支持单行文本:
文本状态表示元素值的单行纯文本编辑控件。
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;
}
我想分享一下Shog9批准答案的编辑版本。
正如Mike Samuel在评论中指出的那样,该函数可以执行内联javascript代码。但Shog9说“让浏览器为你做……”是对的
所以…这里是我的编辑版本,使用DOMParser:
function strip(html){
let doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || "";
}
这里是测试内联javascript的代码:
strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")
此外,它不会在解析时请求资源(如图像)
strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")
对公认答案的改进。
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请求。