Created
February 22, 2011 06:12
-
-
Save chalkers/838286 to your computer and use it in GitHub Desktop.
Pass in a jQuery representation of an element ($container) you get markdown out.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function htmlToMarkdown($container) { | |
var $clone = $container.clone(); | |
$("*",$clone).removeAttr("name").removeAttr("title").removeAttr("id") | |
var html = $clone.html(); | |
html = standardiseHTML(html); | |
html = html.replace(/<a [^h]*href=["']([^"']*)["'][^>]*>([^<]*)<\/a>/gi, " [$2]($1)"); | |
html = html.replace(/<em[^>]*>([^<]*)<\/em>/gi,"*$1*"); | |
html = html.replace(/<strong[^>]*>([^<]*)<\/strong>/gi,"**$1**"); | |
html = html.replace(/<i[^>]*>([^<]*)<\/i>/gi,"*$1*"); | |
html = html.replace(/<b[^>]*>([^<]*)<\/b>/gi,"**$1**"); | |
html = html.replace(/<p[^>]*>([^<]*)<\/p>/gi,"$1\n\n"); | |
html = html.replace(/<li[^>]*>([^<]*)<\/li>/gi," - $1\n"); | |
html = html.replace(/<ol[^>]*>([^<]*)<\/ol>/gi,"\n\n$1\n"); | |
html = html.replace(/<ul[^>]*>([^<]*)<\/ul>/gi,"\n\n$1\n"); | |
html = html.replace(/<blockquote[^>]*>/gi,"<blockquote>\n"); | |
html = html.replace(/<\/blockquote[^>]*>/gi,"<\/blockquote>\n"); | |
$clone = $("<div />"); | |
if($.browser.msie) { | |
html = html.replace(/\n(.*)\n/gi,"<p>$1</p>") | |
} | |
$clone.html(html); | |
blockquoteToQuote($clone); | |
html = $clone.html(); | |
html = html.replace(/>/g,">").replace(/</g, "<"); | |
html = html.replace(/<\/?[^>]*>/g,""); | |
html = html.replace(/\n /gi,"\n"); | |
html = html.replace(/>[ ]{2,}\[C/g,"> [C"); | |
return "\n" + html; | |
} | |
function standardiseHTML(html) { | |
html = html.replace(/\b/g,"**REPLACE**").replace(/\*\*REPLACE\*\*/g,""); | |
html = html.replace(/<(\/?)(\w+)>/gi, "<$1$2>"); | |
if($.browser.msie) { | |
html = html.replace(/<LI>/g,"</LI><LI>").replace(/<([O|U])L><\/LI>/g,"<$1L>") | |
} else { | |
html = html.replace(/\n\s+/gi," "); | |
} | |
return html; | |
} | |
function blockquoteToQuote($container) { | |
$("blockquote", $container).each(function(){ | |
if($(this).children("blockquote").size()>0) { | |
blockquoteToQuote($(this)); | |
} | |
if($.browser.msie){ | |
$(this).html($(this).html().replace("<P></P>",">")); | |
$("p", $(this)).prepend("> "); | |
$(this).html($(this).html().replace("</P>","\r\n<P>> </P>")); | |
} else { | |
$(this).html($(this).html().replace(/\n/g,"\n > ")); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment