HTML to Markdown Converter — TypeScript 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 TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Pure surface of the HTML to Markdown tool (slug: html-to-markdown).
// Hand-rolled subset — no DOM dependency, so the same algorithm ports to the
// Go CLI twin (Go side: html.UnescapeString). Supported: h1-h6, p, div, span,
// br, hr, strong/b, em/i, del/s, code, pre(+code.language-*), a[href,title],
// img[src,alt], blockquote, ul/ol/li (nesting by 2/4-space indent). Entities
// decode via the shared WHATWG table (./htmlEntities decodeHtml) — full
// coverage, single pass, no double-decode. Unknown tags are transparent;
// stray closers are ignored; unclosed tags at EOF auto-close. Text nodes
// backslash-escape \`*_[] so literal characters cannot masquerade as
// Markdown. A `<` with no closing `>` is the one error.
import { decodeHtml } from './htmlEntities';
export type HtmlToMarkdownResult =
| { output: string; error: null }
/** Empty or whitespace-only input is NOT an error — the tool shows nothing. */
| { output: ''; error: null }
| { output: ''; error: string };
interface ElemNode {
type: 'elem';
tag: string;
attrs: Record<string, string>;
children: Node[];
}
type Node = { type: 'text'; v: string } | ElemNode;
const VOID = new Set(['br', 'hr', 'img', 'meta', 'link', 'input', 'source']);
function escapeMarkdown(s: string): string {
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: string): { nodes: Node[] } | { error: string } {
const roots: Node[] = [];
const stack: ElemNode[] = [];
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: string | null = 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: Record<string, string> = {};
const attrRe = /([a-zA-Z-]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s>]+))?/g;
let am: RegExpExecArray | null;
while ((am = attrRe.exec(body)) !== null) {
// Values stay RAW here; href/src/alt are entity-decoded at use, titles
// stay verbatim so a `"` inside a title cannot break the Markdown link.
attrs[am[1].toLowerCase()] = am[2] ? am[2].slice(1, -1) : '';
}
const elem: Node = { type: 'elem', tag, attrs, children: [] };
top().push(elem);
if (!VOID.has(tag) && !body.endsWith('/')) stack.push(elem);
}
return { nodes: roots };
}
const BLOCK_TAGS = new Set(['p', 'div', 'blockquote', 'pre', 'ul', 'ol', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
function isBlock(n: Node): n is ElemNode {
return n.type === 'elem' && BLOCK_TAGS.has(n.tag);
}
/** Inline content of one block: marks, links, images, escaped text. */
function renderInline(nodes: Node[]): string {
let out = '';
for (const n of nodes) {
if (n.type === 'text') {
out += escapeMarkdown(decodeHtml(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 = decodeHtml(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(decodeHtml(n.attrs.alt ?? '')).trim();
out += `})`;
break;
}
default:
out += renderInline(n.children); // span and unknown tags are transparent
}
}
}
return out;
}
/** Render a sequence of nodes as Markdown blocks. */
function renderBlocks(nodes: Node[]): string[] {
const out: string[] = [];
let para: Node[] = [];
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 is ElemNode => c.type === 'elem' && c.tag === 'code',
);
const langMatch = codeElem ? /language-([\w-]+)/.exec(codeElem.attrs.class ?? '') : null;
const lang = langMatch ? langMatch[1] : '';
const textOf = (nodes2: Node[]): string =>
nodes2
.map((c) => (c.type === 'text' ? decodeHtml(c.v) : textOf(c.children)))
.join('');
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: ElemNode, depth: number): string {
const items = list.children.filter((c): c is ElemNode => c.type === 'elem' && c.tag === 'li');
const ordered = list.tag === 'ol';
const lines: string[] = [];
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.
let inline: Node[] = [];
const nested: string[] = [];
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. */
export function htmlToMarkdown(raw: string): HtmlToMarkdownResult {
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 →