Mini Markdown Parser
function mark(str) {
const lines = str.split`\n`;
let wasLi;
for (let i = 0; i < lines.length; i++) {
const curr = lines[i];
const line = curr.trim();
const hdr = line.split`#`.length - 1;
if (line === '') {
lines[i] = '<br>';
} else if (hdr > 0) {
lines[i] = `<h${hdr} style="margin-bottom:0">
${curr.replace(/#/g, '')}</h${hdr}>`;
} else if (line === '***') {
lines[i] = '<hr>';
} else if (line.startsWith('- ')) {
lines[i] = `${!wasLi ? '<ul>' : ''}
<li>${curr.replace(/-\s+/, '')}</li>`;
wasLi = true;
} else if (wasLi) {
lines[i - 1] += '</ul>\n';
wasLi = false;
}
}
return lines.join`\n`
.replace(/\*\*(.+)\*\*/gm, '<b>$1</b>')
.replace(/_(.+)_/gm, '<i>$1</i>')
.replace(/~~(.+)~~/gm, '<strike>$1</strike>')
.replace(/`(.+)`/gm, '<code>$1</code>');
}
// try it out
const md = document.body.appendChild(document.createElement('div'));
md.style.fontFamily = 'sans-serif';
md.innerHTML = `# Mini Markdown Subset
This is a subset of markdown stuff
## It includes
- headers
- **bold styles**
- _italic styles, <br> multiline fine..._
- \`code style\`
Other than ~~strikethrough~~ that is pretty much it... oh and **hr** tags
***
***
_here is some italic text with some bold text **nested** <br>within it etc..._
`;
md.innerHTML = mark(md.innerHTML);
This code takes a string and formats a few parts of it with markdown syntax. This only handles a small subset of actual markdown.
I was thinking about markdown in code comments last night as I was working on a forthcoming snippet.zone github repo. Anyway, I decided to speed-code the main things I find myself using in markdown so that maybe I can do markdown formatted comments at some point…