有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
最简单的方法:
jQuery(html).text();
它从html字符串中检索所有文本。
其他回答
我对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");
const getTextFromHtml = (t) =>
t
?.split('>')
?.map((i) => i.split('<')[0])
.filter((i) => !i.includes('=') && i.trim())
.join('');
const test = '<p>This <strong>one</strong> <em>time</em>,</p><br /><blockquote>I went to</blockquote><ul><li>band <a href="https://workingclasshistory.com" rel="noopener noreferrer" target="_blank">camp</a>…</li></ul><p>I edited this as a reviewer just to double check</p>'
getTextFromHtml(test)
// 'This onetime,I went toband camp…I edited this as a reviewer just to double check'
下面的代码允许您保留一些html标记,同时剥离所有其他标记
function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
另一个公认不如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;
}
这是一个解决@MikeSamuel安全问题的版本:
function strip(html)
{
try {
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = html;
return doc.documentElement.textContent||doc.documentElement.innerText;
} catch(e) {
return "";
}
}
注意,如果HTML标记不是有效的XML,它将返回一个空字符串(也就是,标记必须关闭,属性必须引用)。这并不理想,但确实避免了潜在的安全漏洞问题。
如果不需要有效的XML标记,可以尝试使用:
var doc = document.implementation.createHTMLDocument("");
但出于其他原因,这也不是一个完美的解决方案。