Convert HTML to plain text in JS without browser environment
Converter HTML to plain text like 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, '');
If you can use jQuery
:
var html = jQuery('<div>').html(html).text();
With TextVersionJS (http://textversionjs.com) you can convert your HTML to plain text. It's pure javascript (with tons of RegExps) so you can use it in the browser and in node.js as well.
In node.js it looks like:
var createTextVersion = require("textversionjs");
var yourHtml = "<h1>Your HTML</h1><ul><li>goes</li><li>here.</li></ul>";
var textVersion = createTextVersion(yourHtml);
(I copied the example from the page, you will have to npm install the module first.)
This simple regular expression works:
text.replace(/<[^>]*>/g, '');
It removes all anchors.
Entities, like <
does not contains <, so there is no issue with this regex.