Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Markdown and Documentation

Writing a Markdown-to-HTML Converter

Build a small Markdown renderer step by step - escaping, block parsing, inline parsing, links and code spans - and learn why production parsers use a syntax tree and why escaping comes first.

The best way to understand a format is to write a parser for it. In this lesson you build a small Markdown-to-HTML converter in about 80 lines. It handles headings, paragraphs, fenced code, block quotes, flat lists, rules, and inline emphasis, code, links and images. It will not be fully CommonMark-compliant (that takes thousands of lines and hundreds of edge-case rules), but it shows the architecture every real parser shares and the one security rule you must never skip: escape first. For the syntax you are implementing, see Markdown Syntax: The Complete Guide.

The plan

flowchart TD
  A["Markdown text"] --> B["Split into lines"]
  B --> C["Block pass: group lines into blocks"]
  C --> D["For each block: inline pass on its text"]
  D --> E["HTML string"]

The block pass decides structure; the inline pass formats text inside it.

Why not a few regular expressions over the whole text? Because Markdown depends on context: # inside a code fence is not a heading, * inside a code span is not emphasis. Handling blocks first, and treating code specially, avoids those traps.

Step 1: escaping

Everything the author writes must be treated as text, never as markup, unless it is markup we create ourselves. The characters that matter in HTML are &, <, > and ". Escape before adding any tags, otherwise a <script> in the source reaches the output.

JavaScript
const escapeHtml = (s) => s
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;')
  .replaceAll('>', '&gt;').replaceAll('"', '&quot;');

This renderer escapes all raw HTML, so authors cannot embed tags at all. Many systems allow some HTML and then run the result through an allow-list sanitiser; that is the harder, riskier design.

Step 2: inline syntax

Inline formatting happens inside a block's text. Code spans must be protected first, because nothing inside backticks is formatted. The technique: replace each code span with a placeholder, format the rest, then put the code back.

Node.js Inline rendering: code, emphasis, links, images

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.

Check the third example: the script tag is neutralised by escaping, and the javascript: URL is replaced by #. A converter without these two protections is an XSS hole. The order matters: protect code, escape, then add our own tags.

Step 3: blocks

The block pass walks the lines once with a small state: are we in a fenced code block, in a list, in a paragraph? A block ends at a blank line or when a line starts a different kind of block.

Node.js A small Markdown-to-HTML 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.

Read the output: the <script> line became an escaped paragraph, the < in the code block is &lt;, and the block quote was rendered by calling render on its inner text, which is how nested structure is handled.

What real parsers add

Our converter is a one-pass transformation. Production parsers (markdown-it, marked, commonmark.js, cmark, pulldown-cmark, and the league/commonmark PHP library this site uses) work differently:

  1. Parse to a syntax tree (AST) of block and inline nodes. Headings, paragraphs, lists, items, emphasis and links are nodes.
  2. Transform the tree. Plugins add heading anchors, table of contents, syntax highlighting, link rewriting or custom blocks.
  3. Render the tree to HTML (or to other formats: PDF, EPUB, plain text).

Real inline parsing follows the CommonMark delimiter-run algorithm, which gets cases like ***a** b* and *a **b*** right where regexes fail. Lists need nesting and "loose versus tight" handling; links support reference definitions and titles; raw HTML and entities need their own rules. If you need correct Markdown, use a library and learn to configure it. Write your own only for a restricted subset, such as comments or chat messages, where you control the grammar.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the converter escape HTML before inserting its own tags?

    Escaping turns author text into harmless characters; the converter then adds only the tags it generates itself.
  2. 2. Why are code spans protected with placeholders first?

    Inside a code span, asterisks and brackets are literal characters, so formatting must skip them.
  3. 3. What does safeUrl protect against?

    A link with a javascript: URL runs code when clicked; allowing only http, https and mailto avoids that.
  4. 4. What do production Markdown parsers build before rendering?

    A tree lets plugins transform headings, links and code before one or more renderers produce output.

Summary

  • A Markdown converter is two passes: blocks first, then inline text within blocks.
  • Escape all author text, protect code spans, and allow only safe URL schemes.
  • Fenced code and context-dependent syntax are why a few global regexes are not enough.
  • Real parsers build an AST, apply plugins, and render; use a library for full CommonMark.
  • This renderer supports a small subset on purpose.

Next: Documentation with Markdown