DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

I Built a Live Markdown Editor With No Library (~40 Lines)

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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
Enter fullscreen mode Exit fullscreen mode

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>`;


Enter fullscreen mode Exit fullscreen mode

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>');


Enter fullscreen mode Exit fullscreen mode

Watch the order (bold before italic).

5. Render live on every keystroke


js
editor.oninput = () => preview.innerHTML = mdToHtml(editor.value);


Enter fullscreen mode Exit fullscreen mode

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)