Skip to content

Instantly share code, notes, and snippets.

@cojahmetov
Created February 5, 2015 19:56
Show Gist options
  • Select an option

  • Save cojahmetov/b7070c6b4085498caba1 to your computer and use it in GitHub Desktop.

Select an option

Save cojahmetov/b7070c6b4085498caba1 to your computer and use it in GitHub Desktop.
#js# Convert html to plain text
//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();
//The DOM conversion is problematic the way you do it.
//This will load all links in the HTML snippet, if the html is not sanitized.
//This should be done via a document fragment that's not attached to the DOM
// Also tags such as <li> can have attributes..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment