Markdown to HTML Converter

Write Markdown, get clean HTML. Live split preview with three themes, a settings panel, and a plugin system you can toggle — all client-side, nothing leaves the browser.

100% client-side Plugin architecture 3 preview themes Settings saved locally

📝Markdown → HTML

input.md
output.html — rendered
Ready

⚙️ Settings

🧩 Plugins

Words
0
Characters
0
Headings
0
Links
Read time
0m

How the converter works

A walkthrough of the two-layer parser — a line-based block scanner and an ordered inline rule table — and of the plugin layer that adds block rules and inline rules without touching the core.

01

Parse Markdown in two layers

Complete

Why learn this

Markdown looks simple until you write a parser. The naive approach — one long chain of regex replaces — collapses the moment a code block contains a heading, or a link text contains asterisks. Every real implementation splits the job in two: a block layer that groups lines into structural chunks, and an inline layer that decorates text inside a chunk. The CommonMark specification formalizes exactly this split, and it is worth reading once end to end; it is the reason your list item stops being converted into an italic run when it contains a star.

What you built

A line-based block scanner that walks the document once. Each line is tested against an ordered table of block rules: fenced code, ATX heading, horizontal rule, table, blockquote, unordered list, ordered list. The first rule that claims a line consumes it and any continuation lines, returns the HTML for that block, and hands back the index to resume from. Anything unclaimed accumulates into a paragraph and gets flushed at the next blank line or structural boundary.

Key concepts

  • Claim-and-resume. A block rule returns { html, next }, never a boolean. That contract is what lets a fenced code block swallow twenty lines and still let the scanner pick up cleanly afterwards.
  • Escape first, format second. The entire source is HTML-escaped before any inline rule runs (unless raw HTML is enabled). Everything after that point produces markup, not user-authored markup.
  • Code spans get placeholders. Inline code is extracted to \u00000\u0000 tokens before emphasis runs, so `*not italic*` survives untouched and is restored last.
  • Escaping the escaper. & must be replaced before <, or the entity ampersands introduced by the first replace get escaped again and readers see &amp;lt;.
  • Tables need lookahead. A pipe table is only a table if the next line is a separator row. The rule peeks one line ahead before claiming, which is why the scanner receives the full line array, not a single line.

Alternative approaches

The pragmatic alternative is a library — marked or markdown-it — which follows the reference spec far more completely than 200 lines of hand-written rules can. They are the right choice for production. This tool hand-rolls the parser because the tutorial's job is to show the mechanism, and because adding a bundled parser would mean shipping a dependency and a build step for a page that otherwise ships zero JavaScript libraries. If you need full CommonMark conformance, use a library; if you need to understand the format, write the rules once.

Browser compatibility

The scanner uses String.prototype.split, match, replace, Array.prototype.push and a plain for loop over lines. No lookbehind assertions, no named groups, no String.prototype.replaceAll. Everything works in any browser from 2018 onward, and the whole page is a single static file with no framework hydration.

Performance notes

A 10,000-word document converts in roughly 4–8 ms: one pass over the lines for blocks, then one pass per text node for the inline rules. Conversion is debounced at 120 ms on input, so a fast typist triggers at most one parse per pause rather than one per keystroke. The output is written to the DOM exactly once per conversion.

Common pitfalls

  • Double-escaping. Order the entity replacements: ampersand, then angle brackets, then quotes. Reversing them corrupts every entity you emit.
  • Emphasis eating list markers. * item is a bullet, not the start of italics. Block rules must run before inline rules, always.
  • Unclosed fences. If a fence never closes, the parser must still emit the rest of the document inside the block instead of looping forever. Track the index and bail at end of input.
  • Greedy link regex. A link pattern that spans across two links on one line merges them. Restrict the URL class to non-space, non-bracket characters.
JS — The block rule table
const BLOCK_RULES = [
  { name: 'fence',     test: l => /^```/.test(l),        run: runFence },
  { name: 'heading',   test: l => /^#{1,6}\s+/.test(l), run: runHeading },
  { name: 'hr',        test: l => /^\s*(---+|\*\*\*+)\s*$/.test(l), run: runHr },
  { name: 'table',     test: (l, i, ls) => /^\s*\|/.test(l) && isSep(ls[i + 1]), run: runTable },
  { name: 'quote',     test: l => /^\s*>\s?/.test(l),  run: runQuote },
  { name: 'ul',        test: l => /^\s*[-*+]\s+/.test(l), run: runUl },
  { name: 'ol',        test: l => /^\s*\d+[.)]\s+/.test(l), run: runOl }
];
JS — Claim-and-resume scanner
function parseBlocks(lines, ctx) {
  const out = [];
  let para = [];
  let i = 0;

  const flush = () => {
    if (para.length) {
      out.push('<p>' + inline(para.join(' '), ctx) + '</p>');
      para = [];
    }
  };

  while (i < lines.length) {
    const line = lines[i];
    if (!line.trim()) { flush(); i++; continue; }

    let claimed = false;
    for (const rule of ctx.blockRules) {
      if (!rule.test(line, i, lines)) continue;
      flush();
      const r = rule.run(lines, i, ctx);   // { html, next }
      out.push(r.html);
      i = r.next;
      claimed = true;
      break;
    }
    if (!claimed) { para.push(line.trim()); i++; }
  }
  flush();
  return out.join('\n');
}
JS — Inline rules run in order
const INLINE_RULES = [
  { name: 'code',    re: /`([^`]+)`/g,             html: (m) => '<code>' + m[1] + '</code>' },
  { name: 'image',   re: /!\[([^\]]*)\]\(([^)\s]+)\)/g,
    html: (m) => '<img src="' + m[2] + '" alt="' + m[1] + '">' },
  { name: 'link',    re: /\[([^\]]+)\]\(([^)\s]+)\)/g,
    html: (m) => '<a href="' + m[2] + '">' + m[1] + '</a>' },
  { name: 'strong',  re: /\*\*([^*]+)\*\*/g,         html: (m) => '<strong>' + m[1] + '</strong>' },
  { name: 'em',      re: /\*([^*]+)\*/g,             html: (m) => '<em>' + m[1] + '</em>' },
  { name: 'del',     re: /~~([^~]+)~~/g,             html: (m) => '<del>' + m[1] + '</del>' }
];
💡 Tip

Order is the whole design. Code spans first, then images (they contain brackets like links), then links, then strong before em — otherwise **bold** is eaten by the single-asterisk rule and you get bold with literal asterisks inside.

02

Extend it with plugins, settings and themes

Complete

Why learn this

Every Markdown dialect is the base syntax plus a stack of extensions — GitHub adds tables and task lists, Discourse adds callouts, Hugo adds shortcodes. Hard-coding each of those into the core parser makes the core unreadable and every new feature a fork. The plugin registry flips that: extensions declare the rule they want to add and the core exposes the two ordered tables, so a new syntax is a new object, not a new branch.

What you built

Three plugins, each toggled independently. Callouts adds a block rule for :::note, :::tip and :::warn fences that render as labelled panels. Footnotes adds an inline rule for [^1] references plus a block rule that collects the definitions and appends a footnote list. Emoji adds an inline rule mapping ~40 shortcodes such as :rocket: to characters. Every plugin is a plain object with id, name, kind, desc, and either a block or an inline rule.

Key concepts

  • Registry, not fork. The parser is constructed with a context object holding blockRules and inlineRules. Enabling a plugin pushes its rule into the right table; disabling it splices it out. The core code never learns the plugin's name.
  • Settings are data. Six options live in one object, persisted to localStorage under one key and read at the top of every conversion. No option is a special case in the parser — each one is checked in a single, named place.
  • Themes are CSS classes. The preview pane carries theme-dark, theme-light or theme-sepia. Switching a theme swaps one class, so the rendered source and the plugin output stay byte-identical across themes.
  • Footnote two-pass. References are emitted during the inline pass, but the definitions only exist below. The pass collects them on the context and the document is finalised at the end, which is why the reference rule can be inline while the list is block-level.

Alternative approaches

The heavyweight alternative is a full GitHub Flavored Markdown parser with an AST: parse once into a node tree, let plugins transform nodes, then serialize. That is the architecturally cleaner design — it makes transforms independent of string position and survives nesting — but it triples the code and needs a serializer. For a single-page tool the ordered-rule registry is the honest middle: extensible, inspectable, and small enough to read in one sitting. If you outgrow it, the rule tables map one-to-one onto a node-vision plugin list.

Browser compatibility

Storage uses localStorage wrapped in try/catch, because Safari in private mode throws on write. Copy uses navigator.clipboard with a hidden-textarea fallback for older browsers, and download uses a Blob plus URL.createObjectURL. If you add raw HTML support to a public page, note that innerHTML assignment is the classic injection surface — the option is off by default here, and any production version should sanitise with a library rather than trusting the input.

Performance notes

Plugin rules cost nothing when disabled — they are absent from the tables, not skipped inside a loop. With all three enabled, conversion of a 2,000-word document with 12 callouts and 6 footnotes takes about 9 ms. Emoji replacement is a single global regex over a 40-key map, which is faster than 40 sequential replaces by an order of magnitude.

Common pitfalls

  • Regex state leaking. A global regex object reused with test() keeps its lastIndex between calls. Block rules that use a shared global regex must reset it or use match instead.
  • Plugin order drift. Two inline rules that both match on the same characters produce different output depending on registration order. Document the order in the plugin's desc so toggling never silently changes results elsewhere.
  • Themes touching output. Never generate markup from the active theme. Theme is presentation; the HTML copy button must return the same bytes in all three themes.
  • Settings that break the parser. Raw HTML passthrough is the one option that can produce unbalanced tags, because the input is trusted. Keep it opt-in and label it as such.
JS — Plugin object & registry
const PLUGINS = [
  {
    id: 'callout',
    name: 'Callouts',
    kind: 'block',
    desc: ':::note / :::tip / :::warn fenced panels',
    block: {
      name: 'callout',
      test: (l) => /^:::(note|tip|warn)\s*$/.test(l),
      run: (lines, i, ctx) => {
        const kind = /^:::(\w+)/.exec(lines[i])[1];
        const body = [];
        let j = i + 1;
        while (j < lines.length && !/^:::\s*$/.test(lines[j])) {
          body.push(lines[j++]);
        }
        return {
          html: '<div class="callout ' + kind + '">' +
                '<span class="callout-label">' + kind + '</span>' +
                parseBlocks(body, ctx) + '</div>',
          next: j + 1
        };
      }
    }
  }
];

function buildCtx(settings, enabled) {
  const ctx = {
    blockRules: BLOCK_RULES.slice(),
    inlineRules: INLINE_RULES.slice(),
    notes: [],
    opts: settings
  };
  for (const p of PLUGINS) {
    if (!enabled[p.id]) continue;
    if (p.block) ctx.blockRules.unshift(p.block);
    if (p.inline) ctx.inlineRules.push(p.inline);
  }
  return ctx;
}
JS — Settings object, persisted
const DEFAULTS = {
  smart: true,        // curly quotes, dashes
  breaks: true,       // newline -> <br>
  raw: false,         // allow embedded HTML
  ids: true,          // heading slugs
  blank: true,        // target=_blank on external
  tables: true        // GFM pipe tables
};

function loadSettings() {
  try {
    const raw = localStorage.getItem('tb-md-settings');
    return raw ? Object.assign({}, DEFAULTS, JSON.parse(raw)) : DEFAULTS;
  } catch (e) {
    return DEFAULTS;   // private mode, quota, corrupt JSON
  }
}

function saveSettings(s) {
  try { localStorage.setItem('tb-md-settings', JSON.stringify(s)); }
  catch (e) { /* storage disabled — run in-memory */ }
}
JS — Slug ids & smart typography
function slugify(text) {
  return text.toLowerCase()
    .replace(/[^\w\s-]/g, '')
    .trim()
    .replace(/\s+/g, '-');
}

function smarten(html) {
  return html
    .replace(/(^|[\s([])"/g, '$1\u201C')
    .replace(/"/g, '\u201D')
    .replace(/(^|[\s([])'/g, '$1\u2018')
    .replace(/'/g, '\u2019')
    .replace(/\s--\s/g, ' \u2014 ')
    .replace(/\.\.\./g, '\u2026');
}
💡 Tip

Give every plugin a visible toggle in the UI, not just an entry in a config file. Users learn the architecture by switching a feature on and watching the output change — and a toggle makes it obvious that themes, settings and plugins are three separate layers, not one blob of options.

Model
claude-sonnet-5-5
Difficulty
Level 10
Dependencies
0
Plugins
3

Built with vanilla JavaScript — no parser library, no framework, no build step beyond Astro's static render. The page ships one hand-written block scanner, one ordered inline rule table, six persisted settings, three preview themes and three toggleable plugins. Conversion of a 2,000-word document runs in under 10 ms; every element of the preview is generated from the text in the textarea.

Lessons Learned — Build Process

Notes from writing a Markdown parser that has to stay readable while being extensible.

🧱
Two layers, never one

The single biggest correctness win was refusing to do inline formatting until the block layer finished. Once blocks are settled, an inline pass over one paragraph cannot accidentally eat a list marker or a fence delimiter. The CommonMark spec separates them for exactly this reason, and copying that structure is cheaper than debugging the alternative.

🧩
The plugin table is the whole API

A plugin is a rule plus a label. Because the registry only ever pushes objects into blockRules or inlineRules, adding emoji support and adding callout panels are the same amount of work — about twenty lines each. The temptation is to give plugins a lifecycle (init, beforeParse, afterRender); resist it until a second plugin genuinely needs it.

🎨
Themes stay out of the parser

Three preview themes are three CSS class scopes, nothing more. Keeping colour out of the generation path means Copy HTML returns identical bytes in all three themes — which is what a reader expects from a converter. It also makes the light and sepia themes a five-minute addition instead of a refactor.

🔐
Raw HTML is opt-in, and says so

Escaping the source before parsing makes the default path safe by construction: every tag in the output was generated by this page. The "allow raw HTML" option deliberately breaks that guarantee so embedded widgets work, so it is off by default and labelled as a trust decision. Anything public-facing should sanitise with a library — MDN's Trusted Types guide is the right starting point.

A converter is only trustworthy if you can see both sides. The split pane exists for that reason: every HTML tag on the right is traceable to a line on the left, and every setting or plugin toggle changes the output in a way you can watch happen. Pair this with the JSON Formatter when you are hand-writing structured data, or the Regex Tester when you are tuning the rules that drive a parser like this one.

Also useful
All ToolBrain tools →

Every tool here is client-side and free. Docs teams writing Markdown by hand often pair this with a no-code publishing workflow — see NoCode Insider for that side of the pipeline.