有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
一个非常好的库是净化html,它是一个纯JavaScript函数,可以在任何环境中使用。
我的案例是React Native,我需要从给定文本中删除所有HTML标记。所以我创建了这个包装函数:
import sanitizer from 'sanitize-html';
const textSanitizer = (textWithHTML: string): string =>
sanitizer(textWithHTML, {
allowedTags: [],
});
export default textSanitizer;
现在,通过使用textSanitizer,我可以获得纯文本内容。
其他回答
我对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");
很多人已经回答了这个问题,但我认为分享我编写的函数可能会有用,该函数可以从字符串中删除HTML标记,但允许您包含一个不希望删除的标记数组。它很短,对我来说一直很好。
function removeTags(string, array){
return array ? string.split("<").filter(function(val){ return f(array, val); }).map(function(val){ return f(array, val); }).join("") : string.split("<").map(function(d){ return d.split(">").pop(); }).join("");
function f(array, value){
return array.map(function(d){ return value.includes(d + ">"); }).indexOf(true) != -1 ? "<" + value : value.split(">")[1];
}
}
var x = "<span><i>Hello</i> <b>world</b>!</span>";
console.log(removeTags(x)); // Hello world!
console.log(removeTags(x, ["span", "i"])); // <span><i>Hello</i> world!</span>
另一个公认不如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;
}
还可以使用出色的htmlparser2纯JSHTML解析器。这里是一个工作演示:
var htmlparser = require('htmlparser2');
var body = '<p><div>This is </div>a <span>simple </span> <img src="test"></img>example.</p>';
var result = [];
var parser = new htmlparser.Parser({
ontext: function(text){
result.push(text);
}
}, {decodeEntities: true});
parser.write(body);
parser.end();
result.join('');
输出将是这是一个简单的示例。
请在此处查看实际操作:https://tonicdev.com/jfahrenkrug/extract-text-from-html
如果您使用类似webpack的工具打包web应用程序,则这在节点和浏览器中都有效。
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'