Markdown is a lightweight markup language with a plain-text-formatting syntax that can be converted to many other output formats. It provides a simple way to add HTML formatting like headings, bold, italic, bulleted lists, images, and so on to the plain text.
In this article, you'll learn how to convert HTML into Markdown in a Node.js application and a web browser using the Turndown library. Turndown is a customizable HTML to Markdown converter written in vanilla JavaScript.
Convert markdown to HTML using Node.js
To use Turndown as a Node.js module, type the following command in your terminal to install it from the NPM registry:
$ npm install turndown --save
After the installation is completed, you'll be able to import the Turndown module into your Node.js application like below:
// import Turndown module
const TurndownService = require('turndown')
Now you can use the Turndown API to easily convert any HTML string to Markdown:
// create an instance of the Turndown service
const turndownService = new TurndownService()
// convert HTML to Markdown
const markdown = turndownService.turndown(`
<h1>JavaScript for Beginners</h1>
<p>Follow <a href="https://attacomsian.com/blog">Atta</a> to learn <b>JavaScript</b> from scratch!</p>
`)
// output Markdown
console.log(markdown)
You should see the following output printed on the console:
JavaScript for Beginners
========================
Follow [Atta](https://attacomsian.com/blog) to learn **JavaScript** from scratch!
Convert markdown to HTML using JavaScript
Turndown can also be used in a web browser to convert HTML to Markdown. Just include the following JavaScript file in your HTML document:
<script src="https://unpkg.com/turndown/dist/turndown.js"></script>
After including the script, you should be able to convert HTML to Markdown by using the same code we've used in the above example:
// create an instance of the Turndown service
const turndownService = new TurndownService()
// convert HTML to Markdown
const markdown = turndownService.turndown(`
<h1>JavaScript for Beginners</h1>
<p>Follow <a href="https://attacomsian.com/blog">Atta</a> to learn <b>JavaScript</b> from scratch!</p>
`)
// output Markdown
console.log(markdown)
In JavaScript, you can even pass DOM nodes as input to Turndown API:
// convert document <body> to Markdown
const markdown = turndownService.turndown(document.body)
// convert first <p> tag to Markdown
const markdown = turndownService.turndown(document.querySelector('p'))
Take a look at the documentation or interactive demo to learn more about Turndown capabilities.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.