Last active
September 11, 2017 21:43
-
-
Save robertvanhoesel/17cdda718065e9ac79ec836acc25cf2b to your computer and use it in GitHub Desktop.
Crowded's simple but bulletproof markdown filter
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
/** | |
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, '`').replace(/\\\*/g, '*').replace(/\\\_/g, '_').replace(/\\\~/g, '~'); // 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