我有一个 CouchDB 视图映射函数,可以生成存储的 HTML 文档的摘要(文本的前
x
字符)。不幸的是我没有浏览器环境来将 HTML 转换为纯文本。
目前我使用这个多阶段正则表达式
html.replace(/<style([\s\S]*?)<\/style>/gi, ' ')
.replace(/<script([\s\S]*?)<\/script>/gi, ' ')
.replace(/(<(?:.|\n)*?>)/gm, ' ')
.replace(/\s+/gm, ' ');
虽然它是一个非常好的过滤器,但它显然不是一个完美的过滤器,有时会漏掉一些剩菜。有没有更好的方法可以在没有浏览器环境的情况下转换为纯文本?
这个简单的正则表达式有效:
text.replace(/<[^>]*>/g, '');
它会删除所有锚点。
实体,如
<
不包含 <, so there is no issue with this regex.
将 HTML 转换为纯文本(例如 Gmail):
html = html.replace(/<style([\s\S]*?)<\/style>/gi, '');
html = html.replace(/<script([\s\S]*?)<\/script>/gi, '');
html = html.replace(/<\/div>/ig, '\n');
html = html.replace(/<\/li>/ig, '\n');
html = html.replace(/<li>/ig, ' * ');
html = html.replace(/<\/ul>/ig, '\n');
html = html.replace(/<\/p>/ig, '\n');
html = html.replace(/<br\s*[\/]?>/gi, "\n");
html = html.replace(/<[^>]+>/ig, '');
如果你可以使用
jQuery
:
var html = jQuery('<div>').html(html).text();
使用 TextVersionJS (https://github.com/EDMdesigner/textversionjs),您可以将 HTML 转换为纯文本。它是纯 JavaScript(带有大量正则表达式),因此您也可以在浏览器和 Node.js 中使用它。
在node.js中它看起来像:
var createTextVersion = require("textversionjs");
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
(我从页面复制了示例,您必须先 npm 安装该模块。)
你可以试试这个方法。
textContent
和 innerText
它们都不兼容所有浏览器:
var temp = document.createElement("div");
temp.innerHTML = html;
return temp.textContent || temp.innerText || "";
将@EpokK html 答案更新为电子邮件文本版本用例
const htmltoText = (html: string) => {
let text = html;
text = text.replace(/\n/gi, "");
text = text.replace(/<style([\s\S]*?)<\/style>/gi, "");
text = text.replace(/<script([\s\S]*?)<\/script>/gi, "");
text = text.replace(/<a.*?href="(.*?)[\?\"].*?>(.*?)<\/a.*?>/gi, " $2 $1 ");
text = text.replace(/<\/div>/gi, "\n\n");
text = text.replace(/<\/li>/gi, "\n");
text = text.replace(/<li.*?>/gi, " * ");
text = text.replace(/<\/ul>/gi, "\n\n");
text = text.replace(/<\/p>/gi, "\n\n");
text = text.replace(/<br\s*[\/]?>/gi, "\n");
text = text.replace(/<[^>]+>/gi, "");
text = text.replace(/^\s*/gim, "");
text = text.replace(/ ,/gi, ",");
text = text.replace(/ +/gi, " ");
text = text.replace(/\n+/gi, "\n\n");
return text;
};
如果你想要准确的东西并且可以使用 npm 包,我会使用 html-to-text。
来自自述文件:
const { htmlToText } = require('html-to-text');
const html = '<h1>Hello World</h1>';
const text = htmlToText(html, {
wordwrap: 130
});
console.log(text); // Hello World
仅供参考,我在 npm 趋势上发现了这一点; html-to-text 似乎是我的用例的最佳选择,但您可以在此处查看其他选项。
很简单,你也可以实现一个“toText”原型:
String.prototype.toText = function(){
return $(html).text();
};
//Let's test it out!
var html = "<a href=\"http://www.google.com\">link</a> <br /><b>TEXT</b>";
var text = html.toText();
console.log("Text: " + text); //Result will be "link TEXT"