)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Mini Markdown Parser

  1. function mark(str) {
  2.   const lines = str.split`\n`;
  3.   let wasLi;
  4.  
  5.   for (let i = 0; i < lines.length; i++) {
  6.     const curr = lines[i];
  7.     const line = curr.trim();
  8.     const hdr = line.split`#`.length - 1;
  9.  
  10.     if (line === '') { 
  11.       lines[i] = '<br>';
  12.     } else if (hdr > 0) {
  13.       lines[i] = `<h${hdr} style="margin-bottom:0">
  14.         ${curr.replace(/#/g, '')}</h${hdr}>`;
  15.     } else if (line === '***') {
  16.       lines[i] = '<hr>';
  17.     } else if (line.startsWith('- ')) {
  18.       lines[i] = `${!wasLi ? '<ul>' : ''}
  19.         <li>${curr.replace(/-\s+/, '')}</li>`;
  20.       wasLi = true;
  21.     } else if (wasLi) {
  22.       lines[i - 1] += '</ul>\n';
  23.       wasLi = false;
  24.     }
  25.   }
  26.  
  27.   return lines.join`\n`
  28.     .replace(/\*\*(.+)\*\*/gm, '<b>$1</b>')
  29.     .replace(/_(.+)_/gm, '<i>$1</i>')
  30.     .replace(/~~(.+)~~/gm, '<strike>$1</strike>')
  31.     .replace(/`(.+)`/gm, '<code>$1</code>');
  32. }
  33.  
  34. // try it out
  35.  
  36. const md = document.body.appendChild(document.createElement('div'));
  37. md.style.fontFamily = 'sans-serif';
  38. md.innerHTML = `# Mini Markdown Subset
  39.  
  40. This is a subset of markdown stuff
  41.  
  42. ## It includes
  43.  
  44. - headers
  45. - **bold styles**
  46. - _italic styles, <br> multiline fine..._
  47. - \`code style\`
  48.  
  49. Other than ~~strikethrough~~ that is pretty much it... oh and **hr** tags
  50. ***
  51. ***
  52. _here is some italic text with some bold text **nested** <br>within it etc..._
  53. `;
  54. 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…

snippet.zone ~ 2021-24 /// {s/z}