Sergey Stepnev Sergey Stepnev - 1 year ago 153
HTML Question

HTML to Text Converter for Email Template (javascript)

I want make javascript HTML converter to Text. All done I works good, but I can't process links. I need the reg expression which is make in text version link as

Html version:

<a href="">Link text</a>

convert link to Text version:

Link text(

My code

$('body').on('click','[data-action="convertTemplateToText"]', function() {
var html = $("#clientHTML").val();

if (html) {
html = html.replace(/<!doctype.*>/i,"");
html = html.replace(/<head>[\w\W]*?<\/head>/i,"");
html = html.replace(/<style.*>[\w\W]*?<\/style>/gi,"");
html = html.replace(/<script.*>[\w\W]*?<\/script>/gi,"");
html = html.replace(/\n|\r/g," ");
html = html.replace(/\<\/p\>/gi,"\n");
html = html.replace(/\<\/li\>/gi," ");
html = html.replace(/\<br\s*?\/?\>/gi,"\n");
html = strip_tags(html,'<a>');
html = html_entity_decode(html,'HTML_ENTITIES');
html = html.replace(/([ \t])+/g," ");
html = html.replace(/\n /g,"\n");

if (html.charAt(0) == ' ') {
html = html.substr(1);
} else {
html = '';


return false;

Help me please

Answer Source

I don't know if you're using jQuery or not, but with it it's pretty simple:

$('a').each(function() {
    var $text = $(this).html();
    var $link = $(this).attr('href');
    $(this).after($text+" ("+$link+")");

EDIT3 (corrected error from comment):

OK, I've achieved what you need:


And the substitution would be:

$2 ($1)

Here's a working example:

I've also added a check to include malformed tags such as < a href = ""> or < / a >

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download