Skip to content

Instantly share code, notes, and snippets.

@MartijnR
Last active December 17, 2015 17:19
Show Gist options
  • Save MartijnR/5644798 to your computer and use it in GitHub Desktop.
Save MartijnR/5644798 to your computer and use it in GitHub Desktop.
mardownToHtml JQuery plugin
$.fn.markdownToHtml = function () {
return this.each(function () {
var html,
$childStore = $('<div/>');
$(this).children().each(function (index) {
var name = '$$$' + index;
$(this).clone().markdownToHtml().appendTo($childStore);
$(this).replaceWith(name);
});
html = $(this).html();
html = html.replace(/__([^\s].*[^\s])__/gm, "<strong>$1</strong>");
html = html.replace(/\*\*([^\s].*[^\s])\*\*/gm, "<strong>$1</strong>");
html = html.replace(/_([^\s].*[^\s])_/gm, '<em>$1</em>');
html = html.replace(/\*([^\s].*[^\s])\*/gm, '<em>$1</em>');
//only replaces if url is valid (worthwhile feature?)
html = html.replace(/\[(.*)\]\(((https?:\/\/)(([\da-z\.\-]+)\.([a-z\.]{2,6})|(([0-9]{1,3}\.){3}[0-9]{1,3}))([\/\w \.\-]*)*\/?[\/\w \.\-\=\&\?]*)\)/gm, '<a href="$2">$1</a>');
html = html.replace(/\n/gm, '<br />');
$childStore.children().each(function(i){
var regex = new RegExp('\\$\\$\\$' + i);
html = html.replace(regex, $(this)[0].outerHTML);
});
$(this).text('').append(html);
});
};
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment