Build a Markdown Previewer App with JavaScript
A Markdown previewer shows formatted text as you type — write # Hello on the left, see a big heading on the right. It is the tool behind every README editor and blogging platform, and building a simple one teaches you string parsing, live rendering, and layout in one project.
What you are building
A split screen: a textarea on the left, a preview pane on the right. As the user types Markdown, the preview updates instantly. Support headings, bold, italic, links, lists, and code blocks.
The simplest parser
You do not need a library for the basics. A few regular expressions cover the most-used Markdown:
function renderMarkdown(text) { let html = text .replace(/^### (.*)$/gm, "<h3>$1</h3>") .replace(/^## (.*)$/gm, "<h2>$1</h2>") .replace(/^# (.*)$/gm, "<h1>$1</h1>") .replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>") .replace(/\*(.*?)\*/g, "<em>$1</em>") .replace(/`(.*?)`/g, "<code>$1</code>") .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank">$1</a>') .replace(/^\- (.*)$/gm, "<li>$1</li>"); return html; } document.getElementById("editor").addEventListener("input", (event) => { document.getElementById("preview").innerHTML = renderMarkdown(event.target.value); }); Order matters here: headings must be replaced before bold and italic, and the m flag lets ^ match the start of each line.
Escaping user input
One thing beginners miss: if you put raw user text into innerHTML, a user can inject HTML. For a personal tool that is fine, but escape < and > first if anyone else will use it:
function escapeHtml(text) { return text .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">"); } Run the escape step before the Markdown replacements, or the replacements themselves will be escaped too.
What to add next
When the simple parser gets messy, switch to the marked library — one script tag and you get full Markdown including tables and code blocks with syntax highlighting. Other good additions: a word count, a copy-HTML button, and saving the draft in localStorage so a refresh does not lose the text.
原文:https://www.a8q9.cn/en/article/build-a-markdown-previewer-app-with-javascript-1125d0.html