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

Mini Markdown with Lists

  1.   const isLi = val => val.match(/(^\s+)?- /)
  2.  
  3.   function mark(str) {
  4.     const lines = str.split`\n`;
  5.     let wasLi = false
  6.     let lastDepth = 0;
  7.     let depth;
  8.  
  9.   for (let i = 0; i < lines.length; i++) {
  10.     let curr = lines[i];
  11.     const line = curr.trim();
  12.     const hdr = line.split`#`.length - 1;
  13.  
  14.     if (line === '') {
  15.       lines[i] = '<br>';
  16.     } else if (hdr > 0) {
  17.       lines[i] = `<h${hdr} style="margin-bottom:0">
  18.         ${curr.replace(/#/g, '')}</h${hdr}>`;
  19.     } else if (line === '***') {
  20.       lines[i] = '<hr>';
  21.     } else if (isLi(curr)) {
  22.       depth = curr.split('-')[0].length + 1;
  23.  
  24.       lines[i] = '';
  25.       if (depth < lastDepth) {
  26.         const diff = (lastDepth - depth) / 2
  27.  
  28.         lines[i] += '</ul>'.repeat(diff);
  29.         lastDepth = depth 
  30.       }
  31.  
  32.       lines[i] += `${depth > lastDepth ? '<ul>' : ''}
  33.         <li>${curr.replace(/-\s+/, '')}</li>`;
  34.  
  35.       lastDepth = depth;
  36.  
  37.       wasLi = true;
  38.     } else if (wasLi) {
  39.       lines[i - 1] = '</ul>\n'.repeat(lastDepth)
  40.       wasLi = false
  41.     }
  42.   }
  43.  
  44.   return lines.join`\n`
  45.     .replace(/\*\*(.+)\*\*/gm, '<b>$1</b>')
  46.     .replace(/_(.+)_/gm, '<i>$1</i>')
  47.     .replace(/~~(.+)~~/gm, '<strike>$1</strike>')
  48.     .replace(/`(.+)`/gm, '<code>$1</code>');
  49. }
  50.  
  51. // try it out
  52.  
  53. const md = document.body.appendChild(document.createElement('div'));
  54. md.style.fontFamily = 'sans-serif';
  55. md.innerHTML = `
  56. #Snippet Zone
  57.  
  58. This snippet renders a subset of markdown. 
  59.  
  60. - **bold** and _italic text_
  61. - lists 
  62.   - this particulate
  63.     - snippet can render 
  64.     - nested
  65.   - lists
  66.  
  67. - _**~~strikethrough text~~**_
  68.  
  69. In a real project you will probably want to use
  70. something more complete like the great <a href="https://github.com/markedjs/marked" target="blank" rel="noopener">marked.js</a> library.
  71. `;
  72. md.innerHTML = mark(md.innerHTML);

This snippet renders a small subset of markdown. This is the same as a post from the other day with the addition of support for nested lists.

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