A live Markdown editor — type on the left, rendered HTML on the right, instantly — with no library. It's escape-then-transform, ~40 lines for a usable subset.
📝 Try it live: https://dev48v.infy.uk/solve/day11-markdown-editor.html
1. Escape HTML FIRST (the security rule)
md = md.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");
So someone typing <script> can't inject it. Every transform after this adds safe tags you control. Skip it and your editor is an XSS hole.
2. Protect fenced code blocks first
Extract
``blocks, swap in placeholders, run the other rules, then restore them — sobold` inside a code sample stays literal. Order of operations matters.
3. Block elements, line by line
js
if (/^# /.test(line)) html += `<h1>${line.slice(2)}</h1>`;
Walk the lines; a # prefix is an h1, - starts a list, > a quote. Group consecutive list lines into one <ul>.
4. Inline styles with regex
js
s.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>');
Watch the order (bold before italic).
5. Render live on every keystroke
js
editor.oninput = () => preview.innerHTML = mdToHtml(editor.value);
Markdown is cheap to re-parse, so full re-render per keystroke is fine — that's the instant split-screen feel.
The takeaway
Escape → protect code → block rules → inline regex → live render. Edit the sample.
Top comments (0)