All questions

Markdown Parser

Premium

Markdown Parser

Every README, comment box, and chat app that accepts Markdown runs a parser like this one. You'll build a focused subset: block-level headings and paragraphs, plus inline bold, italics, code, and links — enough to see the two-layer structure every Markdown engine has. The interesting parts aren't the regexes; they're the ordering (bold before italic, code protected from everything) and escaping raw HTML so a Markdown string can't smuggle in a <script>.

Implement markdownParser(md) returning an HTML string. See CommonMark for the full spec this simplifies.

Signature

function markdownParser(md) {
  // returns an HTML string
}

Examples

markdownParser('# Hello **world**');
// '<h1>Hello <strong>world</strong></h1>'

markdownParser('run `npm i` then read [docs](/help)');
// '<p>run <code>npm i</code> then read <a href="/help">docs</a></p>'
markdownParser('<script>alert(1)</script>');
// '<p>&lt;script&gt;alert(1)&lt;/script&gt;</p>'  — escaped, not executed

Notes

  • Two layers — first split into block lines (#..###### headings need a trailing space; blank lines are dropped; everything else is a <p>), then run inline formatting inside each block.
  • Inline set**bold**<strong>, *italic*/_italic_<em>, `code`<code>, [text](url)<a href>.
  • Order matters — handle ** before *, and keep Markdown inside a `code` span literal (don't re-parse it).
  • Escape first — convert &, <, > before anything, so raw HTML in the source is neutralised (the classic Markdown XSS vector).

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium