Skip to content

HTML to Markdown Converter — JavaScript source

Convert HTML fragments and articles into clean Markdown: headings, emphasis, links, images, lists, quotes and code blocks, all processed locally in your browser with a shareable link.

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

/**
 * html-to-markdown — supported-HTML-subset → Markdown converter.
 *
 * Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
 * CosmoDev polyglot showcase port of the `html-to-markdown` tool.
 * Ported from src/lib/html-to-markdown.ts (the canonical TypeScript lib);
 * the Go CLI twin lives at cli/html-to-markdown/html-to-markdown.go.
 *
 * A hand-rolled single-scan tag parser (no DOM) builds a node forest, then a
 * renderer emits Markdown blocks: h1-h6, p/div/blockquote, pre fences with the
 * language taken from class="language-*", ul/ol with 2-space (ul) and
 * 4-space (ol) nested indent, hr, and br as two-spaces-newline; inline marks
 * strong/b/em/i/del/s/code render empty emphasis as nothing, links keep
 * verbatim titles, images decode alt/src. Unknown tags are transparent,
 * stray closers are ignored, unclosed tags auto-close at EOF, and text nodes
 * backslash-escape \ ` * _ [ ] so literal characters cannot masquerade as
 * Markdown. A '<' with no closing '>' is the one error ("Unclosed tag").
 *
 * Entity decode: JS has no stdlib WHATWG table, so this port decodes numeric
 * (&#NN; / &#xHH;) plus the six named entities (amp lt gt quot apos nbsp) in
 * a single pass — "x &amp;lt; y" stays "x &lt; y", never a tag. (The TS lib
 * uses the shared table via ./htmlEntities decodeHtml; the Go twin uses
 * html.UnescapeString.)
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

const VOID = new Set(['br', 'hr', 'img', 'meta', 'link', 'input', 'source']);
const BLOCK_TAGS = new Set([
  'p', 'div', 'blockquote', 'pre', 'ul', 'ol', 'hr',
  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
]);

// Six named entities + numeric references; unknown names pass through whole.
const NAMED = new Map([
  ['amp', '&'], ['lt', '<'], ['gt', '>'], ['quot', '"'], ['apos', "'"], ['nbsp', ' '],
]);
const ENTITY_RE = /&(#[xX][0-9a-fA-F]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);/g;

function decodeEntities(s) {
  return s.replace(ENTITY_RE, (whole, body) => {
    if (body[0] === '#') {
      const hex = body[1] === 'x' || body[1] === 'X';
      const num = parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10);
      if (num >= 0xd800 && num <= 0xdfff) return whole; // lone surrogate — keep the ref
      if (num < 0 || num > 0x10ffff) return whole;
      return String.fromCodePoint(num);
    }
    return NAMED.get(body) ?? whole;
  });
}

function escapeMarkdown(s) {
  return s.replace(/[\\`*_[\]]/g, '\\$&');
}

/** Parse into a node forest. Attribute values may be double-quoted,
 * single-quoted or bare; a quoted value may contain `>`. */
function parseHtml(raw) {
  const roots = [];
  const stack = [];
  const top = () => (stack.length ? stack[stack.length - 1].children : roots);
  let i = 0;
  while (i < raw.length) {
    const lt = raw.indexOf('<', i);
    if (lt === -1) {
      top().push({ type: 'text', v: raw.slice(i) });
      break;
    }
    if (lt > i) top().push({ type: 'text', v: raw.slice(i, lt) });
    // Find the tag's `>`, skipping quoted attribute values.
    let j = lt + 1;
    let quote = null;
    while (j < raw.length && (raw[j] !== '>' || quote !== null)) {
      if (quote === null && (raw[j] === '"' || raw[j] === "'")) quote = raw[j];
      else if (quote !== null && raw[j] === quote) quote = null;
      j++;
    }
    if (j >= raw.length) return { error: 'Unclosed tag' };
    const inner = raw.slice(lt + 1, j).trim();
    i = j + 1;

    if (inner.startsWith('!--')) continue; // comment
    if (inner.startsWith('!')) continue; // doctype
    const closing = inner.startsWith('/');
    const body = closing ? inner.slice(1) : inner.replace(/\/$/, '');
    const nameMatch = /^([a-zA-Z][a-zA-Z0-9-]*)/.exec(body);
    if (!nameMatch) continue; // not a real tag — browsers would show it as text; we drop it
    const tag = nameMatch[1].toLowerCase();

    if (closing) {
      for (let k = stack.length - 1; k >= 0; k--) {
        if (stack[k].tag === tag) {
          stack.length = k;
          break;
        }
      }
      continue;
    }

    const attrs = Object.create(null);
    const attrRe = /([a-zA-Z-]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?/g;
    let am;
    while ((am = attrRe.exec(body)) !== null) {
      // Values stay RAW here; href/src/alt are entity-decoded at use, titles
      // stay verbatim. The quote-strip mirrors am[2].slice(1, -1): quoted
      // values lose their quotes, bare values lose their first and last
      // characters (same quirk the Go twin keeps for lock-step).
      attrs[am[1].toLowerCase()] = am[2] ? am[2].slice(1, -1) : '';
    }
    const elem = { type: 'elem', tag, attrs, children: [] };
    top().push(elem);
    if (!VOID.has(tag) && !body.endsWith('/')) stack.push(elem);
  }
  return { nodes: roots };
}

function isBlock(n) {
  return n.type === 'elem' && BLOCK_TAGS.has(n.tag);
}

/** Inline content of one block: marks, links, images, escaped text. */
function renderInline(nodes) {
  let out = '';
  for (const n of nodes) {
    if (n.type === 'text') {
      out += escapeMarkdown(decodeEntities(n.v)).replace(/\s+/g, ' ');
    } else {
      switch (n.tag) {
        case 'br':
          out += '  \n';
          break;
        case 'strong':
        case 'b': {
          const inner = renderInline(n.children).trim();
          if (inner) out += `**${inner}**`; // empty emphasis renders as nothing
          break;
        }
        case 'em':
        case 'i': {
          const inner = renderInline(n.children).trim();
          if (inner) out += `*${inner}*`;
          break;
        }
        case 'del':
        case 's': {
          const inner = renderInline(n.children).trim();
          if (inner) out += `~~${inner}~~`;
          break;
        }
        case 'code': {
          const inner = renderInline(n.children).trim();
          if (inner) out += `\`${inner}\``;
          break;
        }
        case 'a': {
          const href = decodeEntities(n.attrs.href ?? '');
          const title = n.attrs.title ? ` "${n.attrs.title}"` : '';
          const label = renderInline(n.children).trim() || href;
          out += `[${label}](${href}${title})`;
          break;
        }
        case 'img': {
          const alt = escapeMarkdown(decodeEntities(n.attrs.alt ?? '')).trim();
          out += `![${alt}](${decodeEntities(n.attrs.src ?? '')})`;
          break;
        }
        default:
          out += renderInline(n.children); // span and unknown tags are transparent
      }
    }
  }
  return out;
}

/** Concatenate the entity-decoded text under nodes (pre content only). */
function textOf(nodes) {
  return nodes.map((c) => (c.type === 'text' ? decodeEntities(c.v) : textOf(c.children))).join('');
}

/** Render a sequence of nodes as Markdown blocks. */
function renderBlocks(nodes) {
  const out = [];
  let para = [];
  const flush = () => {
    if (para.length) {
      const text = renderInline(para).trim();
      if (text) out.push(text);
      para = [];
    }
  };
  for (const n of nodes) {
    if (!isBlock(n)) {
      para.push(n);
      continue;
    }
    flush();
    switch (n.tag) {
      case 'hr':
        out.push('---');
        break;
      case 'p':
        out.push(...[renderInline(n.children).trim()].filter(Boolean));
        break;
      case 'div':
        out.push(...renderBlocks(n.children));
        break;
      case 'blockquote': {
        const inner = renderBlocks(n.children).join('\n\n');
        out.push(
          inner
            .split('\n')
            .map((l) => (l ? `> ${l}` : '>'))
            .join('\n'),
        );
        break;
      }
      case 'pre': {
        const codeElem = n.children.find((c) => c.type === 'elem' && c.tag === 'code');
        const langMatch = codeElem ? /language-([\w-]+)/.exec(codeElem.attrs.class ?? '') : null;
        const lang = langMatch ? langMatch[1] : '';
        const body = textOf((codeElem ?? n).children).replace(/\n+$/, '');
        out.push('```' + lang + '\n' + body + '\n```');
        break;
      }
      case 'ul':
      case 'ol':
        out.push(renderList(n, 0));
        break;
      default: {
        const level = Number(n.tag[1]);
        out.push('#'.repeat(level) + ' ' + renderInline(n.children).trim());
      }
    }
  }
  flush();
  return out;
}

function renderList(list, depth) {
  const items = list.children.filter((c) => c.type === 'elem' && c.tag === 'li');
  const ordered = list.tag === 'ol';
  const lines = [];
  items.forEach((li, idx) => {
    const marker = ordered ? `${idx + 1}.` : '-';
    const indent = ' '.repeat(depth === 0 ? 0 : ordered ? 4 : 2);
    // Split li children into inline content + nested lists.
    const inline = [];
    const nested = [];
    for (const c of li.children) {
      if (c.type === 'elem' && (c.tag === 'ul' || c.tag === 'ol')) nested.push(renderList(c, depth + 1));
      else inline.push(c);
    }
    const text = renderInline(inline).trim();
    lines.push(text ? `${indent}${marker} ${text}` : `${indent}${marker}`);
    for (const sub of nested) lines.push(sub);
  });
  return lines.join('\n');
}

/** Convert the supported HTML subset to Markdown. Never throws — errors
 * travel in the result. Empty or whitespace-only input is NOT an error. */
export function htmlToMarkdown(raw) {
  if (!raw.trim()) return { output: '', error: null };
  const parsed = parseHtml(raw);
  if ('error' in parsed) return { output: '', error: parsed.error };
  return { output: renderBlocks(parsed.nodes).join('\n\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 →