LogIn
I don't have account.
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
Adℹ

Convert Markdown to HTML and HTML to Markdown

Janhavi Rajput
73 Views

#markdown

Amazon Pay offer
Adℹ

Whether you're building a blog, content management system (CMS) or a documentation site, converting between Markdown and HTML is a common task in modern web development.

In this guide, we'll show you how to easily convert Markdown to HTML and HTML back to Markdown using JavaScript libraries like unified, remark, rehype, and turndown.

Why Convert Between Markdown and HTML?

  • Markdown to HTML: Needed for rendering Markdown content in browsers.

  • HTML to Markdown: Useful when editing previously rendered content or importing HTML from external sources.

Required Libraries

To perform these conversions, we'll use the following packages

Task Package
Parse Markdown remark-parse
Convert Markdown AST → HTML AST remark-rehype
Serialize HTML AST → HTML rehype-stringify
Convert HTML → Markdown turndown, turndown-plugin-gfm

Installation

Install all necessary dependencies using npm or yarn:

npm install unified remark-parse remark-rehype rehype-stringify turndown turndown-plugin-gfm

Or using yarn

yarn add unified remark-parse remark-rehype rehype-stringify turndown turndown-plugin-gfm

Setting Up the Markdown ↔ HTML Utility

Now let’s implement a simple yet powerful utility to convert Markdown to HTML and vice versa.


import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import TurndownService from "turndown";
import { gfm } from "turndown-plugin-gfm";

/**
 * Convert Markdown → HTML (synchronous)
 */
const markdownToHtml = (markdown) => {
  const file = unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypeStringify)
    .processSync(markdown);
  return String(file);
};
/**
 * Convert HTML → Markdown
 */
const htmlToMarkdown = (html) => {
  const turndown = new TurndownService({
    headingStyle: "atx", // # Heading
    hr: "---", // Horizontal rule style
    codeBlockStyle: "fenced", // Use ```
    bulletListMarker: "-", // Bullet style
  });
  // Enable GitHub Flavored Markdown (tables, strikethrough, etc.)
  turndown.use(gfm);
  // Handle <pre><code class="language-xxx"> blocks
  turndown.addRule("fencedCodeBlock", {
    filter: (node) =>
      node.nodeName === "PRE" &&
      node.firstChild &&
      node.firstChild.nodeName === "CODE",
    replacement: (content, node) => {
      const className = node.firstChild.getAttribute("class") || "";
      const language = (className.match(/language-(\w+)/) || [])[1] || "";
      return `\n\n\`\`\`${language}\n${node.firstChild.textContent}\n\`\`\`\n\n`;
    },
  });
  return turndown.turndown(html);
};
export const MarkdownUtils = { markdownToHtml, htmlToMarkdown };

How It Works

1. Markdown → HTML

We use the Unified processor to create a pipeline:

  • remarkParse parses Markdown into an abstract syntax tree (AST).

  • remarkRehype converts the Markdown AST to a HTML AST.

  • rehypeStringify serializes the HTML AST to a string of HTML.

const html = markdownToHtml("# Hello World");
// Output: <h1>Hello World</h1>

2. HTML → Markdown

We use TurndownService, a powerful HTML-to-Markdown converter. To make it even better, we:

  • Enable GitHub Flavored Markdown via the gfm plugin.
  • Customize code block handling to preserve language syntax highlighting (like language-js).
const markdown = htmlToMarkdown("<h1>Hello</h1>");
// Output: "# Hello"

Example Usage


import { MarkdownUtils } from "./MarkdownUtils";

const md = `
# Sample Title
- List item
- Another item
\`\`\`js
console.log("Hello World");
\`\`\`
`;

const html = MarkdownUtils.markdownToHtml(md);
console.log("HTML Output:\n", html);

const markdownBack = MarkdownUtils.htmlToMarkdown(html);
console.log("Markdown Output:\n", markdownBack);

Use Cases

  • Markdown editors
  • Static site generators
  • Content migration tools
  • Developer blogs
  • Comment systems (e.g., GitHub-style)

Tips

  • Avoid XSS vulnerabilities: Sanitize HTML if you're converting user-generated Markdown.
  • Handle edge cases: Some complex HTML might not convert back to perfect Markdown test thoroughly.
  • Internationalization: Consider encoding and character set issues if working with multilingual content.
Responses (0)

Write a response

CommentHide Comments

No Comments yet.

"},"4":{"id":4,"name":"ZEBRONICS Blanc mouse ad","otherData":"{}","contentFormat":2,"content":"
Sponsored -53%
Zebronics #1 Best Seller

ZEBRONICS Blanc Slim Wireless Mouse — Rechargeable, BT + 2.4GHz (Black)

Up to 1600 DPI · Silent clicks · 63g · Multicolor LED

★★★★★ 4.0 (9,512) 5K+ bought last month
₹376 M.R.P. ₹799Save ₹423
Buy Now
"},"2":{"id":2,"name":"Crousal Ads","otherData":"{}","contentFormat":2,"content":"
Sponsored -34%
iQOO Amazon's Choice

iQOO Z10 Lite 5G — Cyber Green, 4GB RAM, 128GB Storage

Dimensity 6300 · 50MP Sony AI Camera · 6000 mAh · IP64

★★★★★ 4.0 (2,052) 500+ bought last month
₹18,997 M.R.P. ₹28,999Save ₹10,002
Buy Now
"},"1":{"id":1,"name":"Banner Ads","otherData":"{}","contentFormat":2,"content":"\n
\n \n \n \"Amazon\n \n
"}}},"blogDetails":{"isWriter":false,"likes":0,"isLikedByUser":false,"tagIds":[90,366],"tags":[{"id":90,"name":"React","maskingName":"react","isFeatured":true},{"id":366,"name":"Markdown","maskingName":"markdown","isFeatured":false}],"comments":[],"bookmark":{"isBookmarked":false,"count":0},"author":{"userId":"MjlfNF84LVsxNV0ybi10Q19BTmdlX19JdA==","name":"Janhavi Rajput"},"viewCount":72,"showBannerImage":false,"seoTags":null,"content":"

Whether you're building a blog, content management system (CMS) or a documentation site, converting between Markdown and HTML is a common task in modern web development.

\n

In this guide, we'll show you how to easily convert Markdown to HTML and HTML back to Markdown using JavaScript libraries like unified, remark, rehype, and turndown.

\n

Why Convert Between Markdown and HTML?

\n\n

Required Libraries

\n

To perform these conversions, we'll use the following packages

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
TaskPackage
Parse Markdownremark-parse
Convert Markdown AST → HTML ASTremark-rehype
Serialize HTML AST → HTMLrehype-stringify
Convert HTML → Markdownturndown, turndown-plugin-gfm
\n

Installation

\n

Install all necessary dependencies using npm or yarn:

\n
npm install unified remark-parse remark-rehype rehype-stringify turndown turndown-plugin-gfm\n
\n

Or using yarn

\n
yarn add unified remark-parse remark-rehype rehype-stringify turndown turndown-plugin-gfm\n
\n

Setting Up the Markdown ↔ HTML Utility

\n

Now let’s implement a simple yet powerful utility to convert Markdown to HTML and vice versa.

\n
\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport remarkRehype from \"remark-rehype\";\nimport rehypeStringify from \"rehype-stringify\";\nimport TurndownService from \"turndown\";\nimport { gfm } from \"turndown-plugin-gfm\";\n\n/**\n * Convert Markdown → HTML (synchronous)\n */\nconst markdownToHtml = (markdown) => {\n  const file = unified()\n    .use(remarkParse)\n    .use(remarkRehype)\n    .use(rehypeStringify)\n    .processSync(markdown);\n  return String(file);\n};\n/**\n * Convert HTML → Markdown\n */\nconst htmlToMarkdown = (html) => {\n  const turndown = new TurndownService({\n    headingStyle: \"atx\", // # Heading\n    hr: \"---\", // Horizontal rule style\n    codeBlockStyle: \"fenced\", // Use ```\n    bulletListMarker: \"-\", // Bullet style\n  });\n  // Enable GitHub Flavored Markdown (tables, strikethrough, etc.)\n  turndown.use(gfm);\n  // Handle <pre><code class=\"language-xxx\"> blocks\n  turndown.addRule(\"fencedCodeBlock\", {\n    filter: (node) =>\n      node.nodeName === \"PRE\" &&\n      node.firstChild &&\n      node.firstChild.nodeName === \"CODE\",\n    replacement: (content, node) => {\n      const className = node.firstChild.getAttribute(\"class\") || \"\";\n      const language = (className.match(/language-(\\w+)/) || [])[1] || \"\";\n      return `\\n\\n\\`\\`\\`${language}\\n${node.firstChild.textContent}\\n\\`\\`\\`\\n\\n`;\n    },\n  });\n  return turndown.turndown(html);\n};\nexport const MarkdownUtils = { markdownToHtml, htmlToMarkdown };\n
\n

How It Works

\n

1. Markdown → HTML

\n

We use the Unified processor to create a pipeline:

\n\n
const html = markdownToHtml(\"# Hello World\");\n// Output: <h1>Hello World</h1>\n
\n

2. HTML → Markdown

\n

We use TurndownService, a powerful HTML-to-Markdown converter. To make it even better, we:

\n\n
const markdown = htmlToMarkdown(\"<h1>Hello</h1>\");\n// Output: \"# Hello\"\n
\n

Example Usage

\n
\nimport { MarkdownUtils } from \"./MarkdownUtils\";\n\nconst md = `\n# Sample Title\n- List item\n- Another item\n\\`\\`\\`js\nconsole.log(\"Hello World\");\n\\`\\`\\`\n`;\n\nconst html = MarkdownUtils.markdownToHtml(md);\nconsole.log(\"HTML Output:\\n\", html);\n\nconst markdownBack = MarkdownUtils.htmlToMarkdown(html);\nconsole.log(\"Markdown Output:\\n\", markdownBack);\n
\n

Use Cases

\n\n

Tips

\n","categoryId":90,"subCategoryId":90,"contentFormat":5,"blogId":19,"userId":"MjlfNF84LVsxNV0ybi10Q19BTmdlX19JdA==","title":"Convert Markdown to HTML and HTML to Markdown","url":"convert-markdown-to-html-and-html-to-markdown","bannerImage":"","seoDescription":"","generatedOn":"2025-09-27T20:58:33","updatedOn":"2025-09-27T20:58:33"},"popularContents":[{"id":172,"title":"Google L4 Software Engineer III interview experience | Selected","url":"google-l4-software-engineer-iii-interview-experience-selected","description":null,"seoDescription":"Google L4 Software Engineer III interview experience with API design, Googlyness, route matching, graph coding rounds, follow-up questions and tips.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469809Z","viewCount":0},{"id":166,"title":"System Design Interview – BIGGEST Mistakes to Avoid","url":"system-design-interview-biggest-mistakes-to-avoid","description":null,"seoDescription":"Learn the biggest mistakes to avoid in a system design interview, from unclear requirements to poor trade-off analysis. Includes real-world cases, advanced insights and examples to help you ace your next system design interview.","contentType":2,"generatedOn":"2026-10-14T22:55:46.4464426Z","viewCount":0},{"id":138,"title":"DSA Patterns for Coding Interviews: Complete LeetCode Roadmap (Beginner to Advanced)","url":"dsa-patterns-for-coding-interviews-complete-leetcode-roadmap-beginner-to-advanced","description":null,"seoDescription":"Master every LeetCode pattern for coding interviews. Learn Arrays, Sliding Window, Graphs, Dynamic Programming, Trees, Heaps and more with 250+ curated problem","contentType":5,"generatedOn":"2026-10-14T22:55:46.446974Z","viewCount":0},{"id":130,"title":"Rippling SDE-2 Interview Experience (4+ Years Experience) | Offer Received | Coding, LLD & System Design","url":"rippling-sde-2-interview-experience-4-years-experience-offer-received-coding-lld-system-design","description":null,"seoDescription":"Detailed Rippling SDE-2 interview experience with complete 5 rounds, coding questions, rules engine design, system design and preparation tips.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469724Z","viewCount":0},{"id":197,"title":"My Adobe SDE Interview Experience (Aug 2026) 5 Rounds, Selected","url":"my-adobe-sde-interview-experience-aug-2026-5-rounds-selected","description":null,"seoDescription":"Real Adobe SDE interview: 5 rounds, 4 DSA problems (Rotate Array, BSTs, Kth Smallest Matrix), code review & behavioral round. Full solutions + tips.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469842Z","viewCount":0},{"id":173,"title":"Uber SDE-2 Interview Experience : LLD, HLD, DSA & Hiring Manager Round","url":"uber-sde-2-interview-experience-lld-hld-dsa-hiring-manager-round","description":null,"seoDescription":"Read a real Uber SDE-2 interview experience covering DSA, low-level design, high-level system design, behavioral rounds, hiring freeze and key takeaways.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469825Z","viewCount":0},{"id":34,"title":"System Design Deep Dive: 25 Essential Interview Questions","url":"system-design-deep-dive-25-essential-interview-questions","description":null,"seoDescription":"","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469652Z","viewCount":0},{"id":118,"title":"JioHotstar Staff Software Engineer Interview Experience (Bangalore)","url":"jiohotstar-staff-software-engineer-interview-experience-bangalore","description":null,"seoDescription":"JioHotstar Staff Software Engineer interview experience covering Uber system design, API rate limiter LLD, leadership rounds, bar raiser and HR insights.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469709Z","viewCount":0},{"id":35,"title":"Cursor vs Copilot : Which AI Coding Assistant Wins in 2025?","url":"cursor-vs-copilot-which-ai-coding-assistant-truly-wins-in-2025","description":null,"seoDescription":"Compare Cursor vs GitHub Copilot on speed, context awareness, multi-file support, pricing and code quality to choose the best AI coding assistant for developers","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469692Z","viewCount":0},{"id":168,"title":"Amazon SDE-2 Interview Experience (3 Years Experience)","url":"amazon-sde-2-interview-experience-3-years-experience","description":null,"seoDescription":" Read a real Amazon SDE-2 interview experience covering the online assessment, coding rounds, object-oriented design, leadership principles and system design.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4469761Z","viewCount":0}],"latestContents":[{"id":219,"title":"6 Tools That Made My Life Easier as a Software Engineer","url":"6-tools-that-made-my-life-easier-as-a-software-engineer","description":null,"seoDescription":"The 6 developer tools I use daily as a software engineer: Git, VS Code, Docker, Postman, Chrome DevTools, and AI assistants, with real tips, mistakes, and trade","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459466Z","viewCount":0},{"id":218,"title":"When Should a Business Use Multiple AI Agents Instead of One?","url":"when-should-a-business-use-multiple-ai-agents-instead-of-one","description":null,"seoDescription":"Single agent or multi-agent AI? Learn the 4 signals that justify splitting agents by knowledge, permissions, and risk, plus routing and handoff tips.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459502Z","viewCount":0},{"id":216,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459515Z","viewCount":0},{"id":217,"title":"AI in Clinical Trials Market Estimated to Experience a Hike in Growth by 2035","url":"ai-in-clinical-trials-market-estimated-to-experience-a-hike-in-growth-by-2035","description":null,"seoDescription":"The exclusive information about market dynamics serves as a valuable guide to predict economic scenarios and initiatives taken to enhance future growth. Our mar","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459525Z","viewCount":0},{"id":215,"title":"What Happens When an AI Agent Doesn't Know the Answer?","url":"what-happens-when-an-ai-agent-doesnt-know-the-answer","description":null,"seoDescription":"Most AI agents fail quietly. They guess instead of saying \"I don't know.\" Here's how to design better fallback and human-handoff behavior.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459536Z","viewCount":0},{"id":214,"title":"Greedy Algorithms Explained: How They Work, When They Fail and How to Use Them","url":"greedy-algorithms-explained-how-they-work-when-they-fail-and-how-to-use-them","description":null,"seoDescription":"Learn greedy algorithms step by step with C# code Dijkstra, Huffman coding, knapsack and MSTs plus when greedy fails and how to prove it's correct","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459549Z","viewCount":0},{"id":213,"title":"Amazon SDE II Interview Experience (Bangalore, Selected) ~ Aug 2026","url":"amazon-sde-ii-interview-experience-bangalore-selected-aug-2026","description":null,"seoDescription":"Amazon SDE II interview experience from Bangalore covering 4 rounds, DSA, LLD, system design, Leadership Principles, coding questions and selection.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459583Z","viewCount":0},{"id":212,"title":"How to Get 10x Better AI Answers Without Writing Better Prompts : 10 Proven Techniques","url":"how-to-get-10x-better-ai-answers-without-writing-better-prompts-10-proven-techniques","description":null,"seoDescription":"Get better AI answers without complex prompts. Learn 10 practical techniques using context, examples, tools, feedback, and verification.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459596Z","viewCount":0},{"id":211,"title":"I Interviewed for a Microsoft SDE I Role. Here's Everything That Happened.","url":"i-interviewed-for-a-microsoft-sde-i-role-heres-everything-that-happened","description":null,"seoDescription":"My real Microsoft SDE I interview experience, all 4 rounds, the exact DSA problems with fully tested solutions, the WhatsApp system design round","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459607Z","viewCount":0},{"id":140,"title":"PolicyBazaar Software Development Engineer (SDE) Interview Experience | DSA, Core CS & System Design","url":"policybazaar-software-development-engineer-sde-interview-experience-dsa-core-cs-system-design","description":null,"seoDescription":"Detailed PolicyBazaar SDE interview experience covering 3 rounds: DSA coding, core CS assessment and system design with key learnings and insights.","contentType":5,"generatedOn":"2026-10-14T22:55:46.4459619Z","viewCount":0}],"relatedContents":[{"id":142,"title":"Stop Using useEffect for Data Fetching: The Modern Way React Pros Build Faster Apps","url":"stop-using-useeffect-for-data-fetching-the-modern-way-react-pros-build-faster-apps","description":null,"seoDescription":"Modern React shifts data fetching from useEffect to React Router loaders, improving performance, structure and UX by resolving data before render smooth UI","contentType":5,"generatedOn":"2026-10-14T22:55:46.4497406Z","viewCount":0},{"id":161,"title":"React 18 vs React 19 – A Complete Guide for Developers","url":"react-18-vs-react-19-a-complete-guide-for-developers","description":null,"seoDescription":"React 18 vs React 19 – A Complete Guide for Developers (Beginner to Advanced), React is the popular and widely used JavaScript library for building user interfaces.","contentType":2,"generatedOn":"2026-10-14T22:55:46.4497459Z","viewCount":0},{"id":156,"title":"Mastering useState in React : A Complete Guide to State Management in Functional Components","url":"mastering-usestate-in-react","description":null,"seoDescription":"Unlock the full potential of the useState hook in React. Learn how to use useState for state management in functional components with examples, pros and cons, performance tips and best practices.","contentType":2,"generatedOn":"2026-10-14T22:55:46.4497479Z","viewCount":0},{"id":155,"title":"Mastering React Hooks : The Complete Guide","url":"mastering-react-hooks-the-complete-guide","description":null,"seoDescription":"Learn everything about React Hooks from useState and useEffect to custom hooks, performance optimization and real-world use cases. Ideal for beginners to advanced developers.","contentType":2,"generatedOn":"2026-10-14T22:55:46.4497491Z","viewCount":0},{"id":123,"title":"How to Integrate Quill.js in a React Application","url":"how-to-integrate-quill-js-in-a-react-application","description":null,"seoDescription":"How to in integrate Quill js editor in react application? step by step guideline of integrating Quill js in react application. Quill.js is a popular open-source WYSIWYG (What You See Is What You Get) rich text editor. It’s known for its flexibility, extensibility, and a great user experience. react quill, react quill npm, quill react, quilljs react, react quill js","contentType":2,"generatedOn":"2026-10-14T22:55:46.4497507Z","viewCount":0}]}}},"source":{"isMobile":false}}; window.__CLIENT_RENDER__ = false;