Markdown to HTML Converter — JavaScript 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 JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// markdown-to-html — escape-first CommonMark subset → HTML renderer. JavaScript
// port (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
// rules run (raw HTML never passes through; security first), using the shared
// five-char escaper inlined here (`&` first so the entities we emit are never
// re-escaped). Supported blocks: #-headings (1-6), --- /***/ ___ rules, ```
// fenced code (markdown inert inside), > blockquotes (recursive), - * +
// unordered lists, N. ordered lists (source numbers stripped), paragraphs
// (soft line breaks joined with \n). Inline precedence: code spans first
// (placeholder-protected), then images, links, bold, italic, strikethrough —
// non-greedy pairs. Not supported (by design, documented): raw HTML, tables,
// setext headings, nested lists, footnotes, autolinks. Empty or
// whitespace-only input is NOT an error — the tool shows nothing. Never throws.
'use strict';
/** Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
* the entities we emit are never re-escaped. */
function encodeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
}
/** Inline pass: code spans first (placeholder-protected), then images, links,
* bold, italic, strikethrough — non-greedy pairs. */
function renderInline(s) {
const codes = [];
let text = s.replace(/`([^`]+)`/g, (_, code) => {
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) => 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 below. */
function isBlockStart(line) {
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, out) {
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 = [];
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 = [];
while (i < lines.length && lines[i].startsWith('> ')) {
quoted.push(lines[i].slice(2));
i++;
}
const inner = [];
renderBlock(quoted, inner);
out.push(`<blockquote>\n${inner.join('\n')}\n</blockquote>`);
continue;
}
if (UL.test(line)) {
const items = [];
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 = [];
while (i < lines.length && OL.test(lines[i])) {
const m = OL.exec(lines[i]);
items.push(`<li>${renderInline(lines[i].slice(m[0].length))}</li>`);
i++;
}
out.push(`<ol>\n${items.join('\n')}\n</ol>`);
continue;
}
const para = [];
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. */
function markdownToHtml(raw) {
const text = raw.replace(/\r\n?/g, '\n').trim();
if (!text) return { output: '', error: null };
const out = [];
for (const block of text.split(/\n{2,}/)) {
renderBlock(
block.split('\n').filter((l) => l.trim() !== ''),
out,
);
}
return { output: out.join('\n'), error: null };
}
// Example:
// markdownToHtml('## Hello *world*')
// → { output: '<h2>Hello <em>world</em></h2>', error: null }
// markdownToHtml('```js\nconst x = 1; // <b>\n```')
// → { output: '<pre><code class="language-js">const x = 1; // <b></code></pre>', error: null }
// markdownToHtml('<script>alert(1)</script>')
// → { output: '<p><script>alert(1)</script></p>', 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 →