Skip to content

Instantly share code, notes, and snippets.

@robertvanhoesel
Last active September 11, 2017 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertvanhoesel/17cdda718065e9ac79ec836acc25cf2b to your computer and use it in GitHub Desktop.
Save robertvanhoesel/17cdda718065e9ac79ec836acc25cf2b to your computer and use it in GitHub Desktop.
Crowded's simple but bulletproof markdown filter
/**
Copyright (c) 2017 Crowded. All rights reserved.
This work is licensed under the terms of the MIT license.
For a copy, see <https://opensource.org/licenses/MIT>.
**/
function simpleMd(text) {
var text = String(text);
text = text.replace(/\\`/g, '&grave;').replace(/\\\*/g, '&ast;').replace(/\\\_/g, '&lowbar;').replace(/\\\~/g, '&#x7E;'); // first html entitize escaped vars
//code block ``` ... ```
text = text.replace(/^```$([\s\S]*?)^```$/gm, function(s){ return '<code>'+s.substring(4, s.length-4)+'</code>' })
//list
text = text.replace(/(^\*\ .*?([\n\r]|$))+/gm, function(s){
var list = '<ul>'
list += s.replace(/^\*\ .*?$/gm, function(s){ return '<li>'+s.substring(2)+'</li>' })
list += '</ul>'
return list;
})
// for inline, first match based on whitespace or string beginning/end, then replace the matched part
//inline code ` ... `
text = text.replace(/(\s|^|[_*~>])`([^\r\n]*?)`(\s|$|[_*~<,.])/gm, function(s){ return s.replace(/`([^\r\n]*?)`(?!`)/gm, function(s){ return '<span class="inline-code">'+s.substring(1, s.length-1)+'</span>' }) })
//strong * ... *
text = text.replace(/(\s|^|[_~`>])\*([^\r\n]*?)\*(\s|$|[_~`<,.])/gm, function(s){ return s.replace(/\*([^\r\n]*?)\*(?!\*)/gm, function(s){ return '<strong>'+s.substring(1, s.length-1)+'</strong>' }) })
//italic _ ... _
text = text.replace(/(\s|^|[*~`>])\_([^\r\n]*?)\_(\s|$|[*~`<,.])/gm, function(s){ return s.replace(/\_([^\r\n]*?)\_(?!\_)/gm, function(s){ return '<em>'+s.substring(1, s.length-1)+'</em>' }) })
//strikethrough ~ ... ~
text = text.replace(/(\s|^|[_*`>])\~([^\r\n]*?)\~(\s|$|[_*`<,.])/gm, function(s){ return s.replace(/\~([^\r\n]*?)\~(?!\~)/gm, function(s){ return '<strike>'+s.substring(1, s.length-1)+'</strike>' }) })
return text;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment