有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
方法1:
function cleanHTML(str){
str.replace(/<(?<=<)(.*?)(?=>)>/g, '<$1>');
}
function uncleanHTML(str){
str.replace(/<(?<=<)(.*?)(?=>)>/g, '<$1>');
}
方法2:
function cleanHTML(str){
str.replace(/</g, '<').replace(/>/g, '>');
}
function uncleanHTML(str){
str.replace(/</g, '<').replace(/>/g, '>');
}
此外,不要忘记,如果用户碰巧发布了一条数学评论(例如:1<2),您不想删除整个评论。浏览器(仅测试了chrome)不将unicode作为html标记运行。如果将所有<替换为<;字符串中的每一个文件,unicode都将显示<为文本,而不运行任何html。我推荐方法2。jquery也能很好地工作$('#element').text();
其他回答
const-htmlParser=new DOMParser().parseFromString(“<h6>用户<p>名称</p></h6>”,'text/html');const textString=htmlParser.body.textContent;console.log(textString)
我只需要去掉<a>标签,并用链接的文本替换它们。
这似乎很有效。
htmlContent= htmlContent.replace(/<a.*href="(.*?)">/g, '');
htmlContent= htmlContent.replace(/<\/a>/g, '');
另一个公认不如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;
}
如果您不想为此创建DOM(可能您不在浏览器上下文中),可以使用striptags npm包。
import striptags from 'striptags'; //ES6 <-- pick one
const striptags = require('striptags'); //ES5 <-- pick one
striptags('<p>An HTML string</p>');
大多数情况下,接受的答案都很好,但是在IE中,如果html字符串为空,则会得到“null”(而不是“”)。固定的:
function strip(html)
{
if (html == null) return "";
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}