Skip to content

Markdown to HTML Converter — TypeScript source

Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.

This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Pure surface of the Markdown to HTML tool (slug: markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything escaped before inline rules (raw
// HTML never passes through; security first), using the shared five-char
// escaper from ./htmlEntities. The supported blocks and the exact inline
// precedence below are the contract a Go CLI twin must reproduce. Not
// supported (by design, documented): raw HTML, tables, setext headings,
// nested lists, footnotes, autolinks.
import { encodeHtml } from './htmlEntities';

export type MarkdownToHtmlResult =
  | { output: string; error: null }
  /** Empty or whitespace-only input is NOT an error — the tool shows nothing. */
  | { output: ''; error: null };

/** Inline pass: code spans first (placeholder-protected), then images, links,
 * bold, italic, strikethrough — non-greedy pairs. */
function renderInline(s: string): string {
  const codes: string[] = [];
  let text = s.replace(/`([^`]+)`/g, (_, code: string) => {
    codes.push(`<code>${encodeHtml(code)}</code>`);
    return `\u0000${codes.length - 1}\u0000`;
  });
  text = encodeHtml(text);
  text = text
    .replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, '<img src="$2" alt="$1">')
    .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '<a href="$2">$1</a>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/__([^_]+)__/g, '<strong>$1</strong>')
    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
    .replace(/_([^_]+)_/g, '<em>$1</em>')
    .replace(/~~([^~]+)~~/g, '<del>$1</del>');
  return text.replace(/\u0000(\d+)\u0000/g, (_, n: string) => codes[Number(n)]);
}

const HEADING = /^(#{1,6}) (.*)$/;
const HR = /^(---+|\*\*\*+|___+)\s*$/;
const UL = /^[-*+] /;
const OL = /^\d+\. /;

/** True when a line STARTS a new block — the paragraph terminator. Any new
 * block type must register here and in the renderBlock dispatch above. */
function isBlockStart(line: string): boolean {
  return (
    HEADING.test(line) || HR.test(line) || line.startsWith('```') || line.startsWith('> ') || UL.test(line) || OL.test(line)
  );
}

/** Render consecutive lines (one blank-line-separated chunk). */
function renderBlock(lines: string[], out: string[]): void {
  let i = 0;
  while (i < lines.length) {
    const line = lines[i];

    const heading = HEADING.exec(line);
    if (heading) {
      const level = heading[1].length;
      out.push(`<h${level}>${renderInline(heading[2].trim())}</h${level}>`);
      i++;
      continue;
    }

    if (HR.test(line)) {
      out.push('<hr>');
      i++;
      continue;
    }

    if (line.startsWith('```')) {
      const lang = line.slice(3).trim();
      const body: string[] = [];
      i++;
      while (i < lines.length && !lines[i].startsWith('```')) {
        body.push(lines[i]);
        i++;
      }
      i++; // past the closing fence (or past the end of an unclosed fence)
      out.push(
        `<pre><code${lang ? ` class="language-${encodeHtml(lang)}"` : ''}>${encodeHtml(body.join('\n'))}</code></pre>`,
      );
      continue;
    }

    if (line.startsWith('> ')) {
      const quoted: string[] = [];
      while (i < lines.length && lines[i].startsWith('> ')) {
        quoted.push(lines[i].slice(2));
        i++;
      }
      const inner: string[] = [];
      renderBlock(quoted, inner);
      out.push(`<blockquote>\n${inner.join('\n')}\n</blockquote>`);
      continue;
    }

    if (UL.test(line)) {
      const items: string[] = [];
      while (i < lines.length && UL.test(lines[i])) {
        items.push(`<li>${renderInline(lines[i].replace(UL, ''))}</li>`);
        i++;
      }
      out.push(`<ul>\n${items.join('\n')}\n</ul>`);
      continue;
    }

    if (OL.test(line)) {
      const items: string[] = [];
      while (i < lines.length && OL.test(lines[i])) {
        items.push(`<li>${renderInline(lines[i].replace(OL, ''))}</li>`);
        i++;
      }
      out.push(`<ol>\n${items.join('\n')}\n</ol>`);
      continue;
    }

    const para: string[] = [];
    while (i < lines.length && !isBlockStart(lines[i])) {
      para.push(renderInline(lines[i].trim()));
      i++;
    }
    out.push(`<p>${para.join('\n')}</p>`);
  }
}

/** Convert the supported Markdown subset to HTML. Never fails. */
export function markdownToHtml(raw: string): MarkdownToHtmlResult {
  const text = raw.replace(/\r\n?/g, '\n').trim();
  if (!text) return { output: '', error: null };
  const out: string[] = [];
  for (const block of text.split(/\n{2,}/)) {
    renderBlock(block.split('\n').filter((l) => l.trim() !== ''), out);
  }
  return { output: out.join('\n'), error: null };
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →