HTML to Markdown Converter With Pure JavaScript – Turndown

Category: Javascript , Recommended , Text | October 31, 2018
Author: domchristie
Views Total: 906
Official Page: Go to website
Last Update: October 31, 2018
License: MIT

Preview:

HTML to Markdown Converter With Pure JavaScript – Turndown

Description:

Turndown is a customizable, standalone JavaScript-based  HTML to Markdown converter for both node.js and browser.

How to use it:

Install the Turndown via NPM:

# NPM
$ npm install turndown --save

Import the Turndown into your module.

// ES 6
import TurndownService from 'turndown';

// CommonJS:
const TurndownService = require('turndown');

For browser, include the JavaScript file ‘turndown.js’ on the webpage.

<script src="https://unpkg.com/turndown/dist/turndown.js"></script>

Create a new Turndown instance.

const turndownService = new TurndownService()

Convert any HTML markup to Markdown.

const markdown = turndownService.turndown('<h1>Hello world!</h1>')

All default options.

new TurndownService({
    rules: COMMONMARK_RULES,
    headingStyle: 'setext',
    hr: '* * *',
    bulletListMarker: '*',
    codeBlockStyle: 'indented',
    fence: '```',
    emDelimiter: '_',
    strongDelimiter: '**',
    linkStyle: 'inlined',
    linkReferenceStyle: 'full',
    br: '  ',
    blankReplacement: function (content, node) {
      return node.isBlock ? '\n\n' : ''
    },
    keepReplacement: function (content, node) {
      return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
    },
    defaultReplacement: function (content, node) {
      return node.isBlock ? '\n\n' + content + '\n\n' : content
    }
})

Add a custom rule to the converter.

turndownService.addRule('rule-name', {
  // your own rule here
})

You’re able to specify the html elements which should be kept while converting.

turndownService.keep(['del', 'ins'])

Changelog:

v5.0.1 (10/31/2018)

  • Do not escape hyphens unnecessarily

You Might Be Interested In:

Leave a Reply