Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Markdown to HTML Converter

Build a small Markdown to HTML converter with regular expressions. Escape HTML safely, convert headings, lists, code, emphasis, links and paragraphs, and learn where regex stops being enough.

Markdown is a friendly target for a regex project because its syntax is regular enough for small cases: # Heading, **bold**, [text](url). In this project you will build a converter for a useful subset in four layers. You will also learn the lesson every real Markdown library teaches: parse the blocks first, then the inline formatting inside them, and always escape HTML before you add your own tags.

Be clear about the goal. This is a learning tool, not a replacement for a proper parser. At the end we will list exactly where the regex approach breaks.

flowchart TD
  M["Markdown text"] --> E["1. Escape HTML characters"]
  E --> B["2. Split into blocks<br/>headings, lists, code, paragraphs"]
  B --> I["3. Inline pass<br/>code, bold, italic, links"]
  I --> H["HTML"]

Escaping first means user text can never inject tags; our own tags are added afterwards.

Layer 1: Escape first

If you convert Markdown to HTML without escaping, a line like <script>alert(1)</script> goes straight into the page. Escape the five special characters before any other step. Everything you add after that is your own markup.

Node.js Layer 1: escaping HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A single replace with a lookup function is safe because each character is replaced once. Chained replaces must handle & first or they will re-escape their own output.

Layer 2: Inline formatting

Inline rules work inside a line of text. Order is important: code spans first (their content must not be formatted), then images and links, then bold, then italic.

Node.js Layer 2: inline rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the italic pattern: (?<![*\w])\*(?=\S)(.+?)(?<=\S)\*(?![*\w]). The lookarounds say the opening star must not follow a word character or another star, must be followed by a non-space, and the closing star must follow a non-space and not be followed by a word character. That is why 2 * 3 * 4 is untouched (stars with spaces around them).

The placeholder trick (\u0000N\u0000) is the standard way to protect text from later rules: extract it, replace it with a token that no rule can match, then restore it at the end.

Layer 3: Blocks

A block parser processes line by line, keeping a little state: are we inside a code fence, a list, or a paragraph? Each line is matched against block patterns in order.

Node.js Layer 3: blocks and the full converter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You now have a working converter in about 50 lines. Try adding a rule: for example, ## Heading {#custom-id} that sets an id attribute, or a table row syntax.

Where regex stops being enough

Be honest about the limits, because they teach you when to switch tools:

  1. Nesting. Lists inside lists, quotes inside lists, emphasis inside link text inside emphasis. Regexes cannot count nesting levels; parsers use a stack or a tree.
  2. Context-dependent rules. CommonMark has precise rules for when * opens or closes emphasis (the "left-flanking delimiter run" algorithm). Our lookarounds approximate it.
  3. Unsafe URLs. [x](javascript:alert(1)) produces a dangerous link. A real converter validates the URL scheme (allow http, https, mailto, relative paths) before output.
  4. Raw HTML pass-through, tables, footnotes, reference-style links: each is a feature that needs structure beyond a one-line pattern.

For production use a maintained Markdown library plus an HTML sanitizer. The skills you practiced here (escape first, protect regions with placeholders, order the rules, test edge cases) apply to any text transformation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why escape HTML characters before converting Markdown?

    Escaping first turns every special character in the source into harmless text, so only the tags the converter adds can be markup.
  2. 2. Why are code spans extracted before applying bold and italic rules?

    The placeholder trick hides code content from all later rules and restores it at the end.
  3. 3. What does (?<=\S) check in the bold pattern?

    It is a lookbehind. Requiring non-space before the closing ** avoids treating ** as formatting in "a ** b **".
  4. 4. Which Markdown feature is hardest for a regex-only converter?

    Nesting needs a stack or a tree, which regular expressions cannot provide.

Summary

  • Convert in layers: escape, split into blocks, format inline.
  • Use placeholders to protect code spans from other rules, then restore them.
  • Order of rules matters; lookarounds approximate the real emphasis rules.
  • Validate URLs and sanitize HTML for anything beyond a toy.
  • Know the limits of regex: nesting and context-sensitive rules need a real parser.

Next: Project: A Template Engine