Skip to content

Instantly share code, notes, and snippets.

@feliperohdee
Created June 21, 2017 23:51
Show Gist options
  • Save feliperohdee/706bfba28c6ed211ead82abadf394607 to your computer and use it in GitHub Desktop.
Save feliperohdee/706bfba28c6ed211ead82abadf394607 to your computer and use it in GitHub Desktop.
lightweight MD like parser
const regex = {
headline: /^(#{1,6})([^#\n]+)$/m,
hr: /^(?:([*\-_] ?)+)\1\1$/gm,
style: /(?:([*_~]{1,3}))([^*_~\n]+[^*_~\s])\1/g
};
export default function(str) {
let stra;
/* headlines */
stra = regex.headline.exec(str);
while (stra !== null) {
const count = stra[1].length;
str = str.replace(stra[0], `<h${count}>${stra[2].trim()}</h${count}>`).trim();
stra = regex.headline.exec(str);
}
/* strikethrough, underline, bold and italic */
for (let i = 0; i < 4; i++) {
stra = regex.style.exec(str);
while (stra !== null) {
let repstr = [];
if (stra[1].indexOf('~~') >= 0) {
str = str.replace(stra[0], `<del>${stra[2]}</del>`);
} else if (stra[1].indexOf('_') >= 0) {
str = str.replace(stra[0], `<u>${stra[2]}</u>`);
} else {
switch (stra[1].length) {
case 1:
repstr = ['<i>', '</i>'];
break;
case 2:
repstr = ['<b>', '</b>'];
break;
case 3:
repstr = ['<i><b>', '</b></i>'];
break;
default:
repstr = ['', ''];
}
str = str.replace(stra[0], repstr[0] + stra[2] + repstr[1]);
}
stra = regex.style.exec(str);
}
}
/* horizontal line */
stra = regex.hr.exec(str);
while (stra !== null) {
str = str.replace(stra[0], '\n<hr/>\n');
stra = regex.hr.exec(str);
}
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment