有没有一种简单的方法可以在JavaScript中获取一串html,并剥离出html?
如果你在浏览器中运行,那么最简单的方法就是[让浏览器为你做这件事......](
)function stripHtml(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
注意:正如人们在评论中指出的那样,如果你不能控制HTML的来源,最好不要这样做(例如,不要在任何可能来自用户输入的东西上运行这个程序)。对于这些情况,你仍然可以*让浏览器为你做这些工作--见Saba关于使用现在广泛使用的DOMParser的回答。
另一个公认的不如nickf'或Shog9'的优雅的解决方案是,从
标签开始递归地行走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;
}