Introduction to Turndown
Turndown is a popular JavaScript library designed to convert HTML into Markdown format. It is incredibly useful for developers who need to convert rich text from HTML to Markdown efficiently. This guide covers various Turndown APIs with examples to help you master the library.
Getting Started
First, you’ll need to install the Turndown library:
npm install turndown
Once installed, you can start converting HTML to Markdown:
const TurndownService = require('turndown') const turndownService = new TurndownService() const html = 'Hello world!
' const markdown = turndownService.turndown(html) console.log(markdown)
Basic API methods
Turndown offers several methods to customize the conversion process:
Keep Method
The keep()
method preserves the content of specified tags:
turndownService.keep(['table', 'tr', 'td'])
Remove Method
The remove()
method removes specific elements:
turndownService.remove(['script', 'style'])
Add Rule Method
With the addRule()
method, you can define custom rules for converting elements:
turndownService.addRule('strikethrough', { filter: 'del', replacement: function(content) { return '~~' + content + '~~' } })
Advanced API usage
Let’s dive into more advanced API usage:
Set Options
You can set options to override the default settings:
turndownService.options = { headingStyle: 'atx', hr: '---', bulletListMarker: '*' }
Escaping Characters
Turndown also provides a way to escape Markdown characters:
turndownService.escape((text) => text.replace(/[*_~]/g, '\\$&'))
App Example
Now, let’s see a simple app example that integrates various Turndown APIs:
HTML to Markdown Converter
This app allows users to input HTML code and get the converted Markdown:
const app = document.querySelector('#app') const input = document.createElement('textarea') const output = document.createElement('pre') const button = document.createElement('button') button.textContent = 'Convert' button.addEventListener('click', () => { const html = input.value const markdown = turndownService.turndown(html) output.textContent = markdown }) app.appendChild(input) app.appendChild(button) app.appendChild(output)
With this example, you have a simple interface to convert HTML input into Markdown with a click of a button!
Feeling inspired to integrate Turndown in your projects? Use this guide to explore the various capabilities and master the art of HTML to Markdown conversion!
Hash: f74f24165ef1a1ad69b0d0660f02cb3e541a1f21a7d23e2c4515641f343a7836