有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
正如其他人所建议的,我建议尽可能使用DOMParser。
然而,如果您恰好在Node/JS Lambda内部工作,或者DOMParser不可用,我会使用下面的正则表达式来匹配前面的回答/评论中提到的大多数场景。它与$gt;不匹配;和$lt;正如其他一些人可能担心的那样,但应该捕捉到几乎任何其他场景。
const dangerousText = '?';
const htmlTagRegex = /<\/?([a-zA-Z]\s?)*?([a-zA-Z]+?=\s?".*")*?([\s/]*?)>/gi;
const sanitizedText = dangerousText.replace(htmlTagRegex, '');
这可能很容易简化,但它应该适用于大多数情况。希望这对某人有所帮助。
其他回答
另一个公认不如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;
}
这应该可以在任何Javascript环境(包括NodeJS)上完成工作。
const text = `
<html lang="en">
<head>
<style type="text/css">*{color:red}</style>
<script>alert('hello')</script>
</head>
<body><b>This is some text</b><br/><body>
</html>`;
// Remove style tags and content
text.replace(/<style[^>]*>.*<\/style>/gm, '')
// Remove script tags and content
.replace(/<script[^>]*>.*<\/script>/gm, '')
// Remove all opening, closing and orphan HTML tags
.replace(/<[^>]+>/gm, '')
// Remove leading spaces and repeated CR/LF
.replace(/([\r\n]+ +)+/gm, '');
我对Jibberboy 2000的原始脚本做了一些修改希望对某人有用
str = '**ANY HTML CONTENT HERE**';
str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");
如果你在浏览器中运行,那么最简单的方法就是让浏览器为你做。。。
function stripHtml(html)
{
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
注意:正如人们在评论中所指出的,如果您不控制HTML的源代码(例如,不要在可能来自用户输入的任何内容上运行此代码),最好避免这种情况。对于这些场景,您仍然可以让浏览器为您完成工作-请参阅Saba关于使用现在广泛可用的DOMParser的回答。
简单的2行jquery去掉html。
var content = "<p>checking the html source </p><p>
</p><p>with </p><p>all</p><p>the html </p><p>content</p>";
var text = $(content).text();//It gets you the plain text
console.log(text);//check the data in your console
cj("#text_area_id").val(text);//set your content to text area using text_area_id