### Installation Source: https://github.com/mixmark-io/turndown/blob/master/README.md Instructions for installing Turndown via npm or directly in the browser. ```APIDOC ## Installation ### npm ```bash npm install turndown ``` ### Browser ```html ``` For usage with RequireJS, UMD versions are located in `lib/turndown.umd.js` (for Node.js) and `lib/turndown.browser.umd.js` for browser usage. These files are generated when the npm package is published. To generate them manually, clone this repo and run `npm run build`. ``` -------------------------------- ### Install Turndown via npm Source: https://github.com/mixmark-io/turndown/blob/master/README.md Install the Turndown package using npm for Node.js projects. ```bash npm install turndown ``` -------------------------------- ### Integrate GitHub Flavoured Markdown Plugin Source: https://github.com/mixmark-io/turndown/wiki/Migrating-from-to-markdown-to-Turndown Use the `turndown-plugin-gfm` plugin to enable GitHub Flavoured Markdown support. Requires installation of the plugin. ```javascript var gfm = require('turndown-plugin-gfm').gfm var turndownService = new TurndownService() turndownService.use(gfm) turndownService.turndown(stringOfHTML) ``` -------------------------------- ### Configure Non-Markdown Element Handling Source: https://github.com/mixmark-io/turndown/wiki/Migrating-from-to-markdown-to-Turndown Customize how non-markdown elements are processed using the `defaultReplacement` option. This example restores the old behavior of to-markdown. ```javascript var turndownService = new TurndownService({ defaultReplacement: function (innerHTML, node) { return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML } }) ``` -------------------------------- ### PHP Code Block Example Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html This snippet demonstrates a PHP code block within a Markdown document. It includes a conditional execution and a call to shell_exec. ```php return 1 < 2 ? shell_exec('echo $input | $markdown_script') : 0; ``` -------------------------------- ### Define Emphasis Rule Source: https://github.com/mixmark-io/turndown/blob/master/README.md Example of a Turndown rule for converting emphasis elements ('em', 'i') to Markdown using a configurable delimiter specified in the options. ```javascript rules.emphasis = { filter: ['em', 'i'], replacement: function (content, node, options) { return options.emDelimiter + content + options.emDelimiter } } ``` -------------------------------- ### Add Custom Rule for Strikethrough Source: https://github.com/mixmark-io/turndown/wiki/Migrating-from-to-markdown-to-Turndown Use the `addRule` method to define custom conversions, replacing the old `converters` option. This example adds a rule for strikethrough elements. ```javascript var turndownService = new TurndownService() turndownService.addRule('strikethrough', { filter: ['del', 's', 'strike'], replacement: function (content) { return '~' + content + '~' } }) turndownService.turndown(stringOfHTML) ``` -------------------------------- ### Custom Default Replacement in Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Specify how Turndown handles unrecognized HTML elements. This example shows preserving unrecognized elements as raw HTML or stripping them while retaining text content. ```javascript var TurndownService = require('turndown') // Custom default replacement - how unrecognized elements are handled var turndownService = new TurndownService({ defaultReplacement: function (content, node) { // Preserve unrecognized elements as HTML (like to-markdown behavior) return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML } }) // Or strip all unrecognized elements var stripService = new TurndownService({ defaultReplacement: function (content, node) { // Return only text content, with spacing for blocks return node.isBlock ? '\n\n' + content + '\n\n' : content } }) ``` -------------------------------- ### Define a Paragraph Rule Source: https://github.com/mixmark-io/turndown/blob/master/README.md Example of a custom rule for Turndown, defining how paragraph elements ('p') should be converted to Markdown. It adds two new lines before and after the paragraph content. ```javascript { filter: 'p', replacement: function (content) { return '\n\n' + content + '\n\n' } } ``` -------------------------------- ### Custom Keep Replacement in Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Define how specific HTML elements, marked for keeping, are represented in the Markdown output. This example adds HTML comments and newlines around kept block elements. ```javascript var TurndownService = require('turndown') // Custom keep replacement - how kept elements appear in output var turndownService = new TurndownService({ keepReplacement: function (content, node) { // Add extra spacing around block-level kept elements if (node.isBlock) { return '\n\n\n' + node.outerHTML + '\n\n\n' } return node.outerHTML } }) turndownService.keep(['video', 'audio']) var result = turndownService.turndown('

Text

') console.log(result) ``` -------------------------------- ### Markdown Fenced Code Block Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html A Markdown fenced code block. Used for multi-line code examples. ```markdown ~~~ ``` ```markdown Code ``` ```markdown ~~~ ``` ```markdown ``` ``` ```markdown Code ``` ```markdown ``` ``` ```markdown ``` ```markdown Code ``` ```markdown ``` -------------------------------- ### Filter Elements with a Function Source: https://github.com/mixmark-io/turndown/blob/master/README.md Shows how to use a function for the 'filter' property in a Turndown rule to conditionally select nodes. This example selects 'A' elements with an 'href' attribute when the 'linkStyle' option is 'inlined'. ```javascript filter: function (node, options) { return ( options.linkStyle === 'inlined' && node.nodeName === 'A' && node.getAttribute('href') ) } ``` -------------------------------- ### Instantiate TurndownService with Options Source: https://github.com/mixmark-io/turndown/blob/master/README.md Create a new TurndownService instance and pass configuration options during initialization. ```javascript var turndownService = new TurndownService({ option: 'value' }) ``` -------------------------------- ### Using Plugins Source: https://github.com/mixmark-io/turndown/blob/master/README.md Demonstrates how to use plugins with the TurndownService instance. Plugins can be used individually or as an array. The `use` method returns the `TurndownService` instance for chaining. ```APIDOC ## `use(plugin|array)` ### Description Use a plugin, or an array of plugins. The `use` method returns the `TurndownService` instance for chaining. ### Method `use` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Import plugins from turndown-plugin-gfm var turndownPluginGfm = require('turndown-plugin-gfm') var gfm = turndownPluginGfm.gfm var tables = turndownPluginGfm.tables var strikethrough = turndownPluginGfm.strikethrough // Use the gfm plugin turndownService.use(gfm) // Use the table and strikethrough plugins only turndownService.use([tables, strikethrough]) ``` ### Response #### Success Response (200) Returns the `TurndownService` instance for chaining. #### Response Example (Instance of TurndownService) ``` -------------------------------- ### Use Turndown Plugins Source: https://github.com/mixmark-io/turndown/blob/master/README.md Demonstrates how to import and use plugins from 'turndown-plugin-gfm' with the TurndownService instance. Supports using single plugins or an array of multiple plugins. ```javascript var turndownPluginGfm = require('turndown-plugin-gfm') var gfm = turndownPluginGfm.gfm var tables = turndownPluginGfm.tables var strikethrough = turndownPluginGfm.strikethrough // Use the gfm plugin turndownService.use(gfm) // Use the table and strikethrough plugins only turndownService.use([tables, strikethrough]) ``` -------------------------------- ### Basic Usage Source: https://github.com/mixmark-io/turndown/blob/master/README.md Demonstrates how to initialize Turndown and convert simple HTML strings or DOM nodes to Markdown. ```APIDOC ## Usage ### Basic Conversion ```js // For Node.js var TurndownService = require('turndown') var turndownService = new TurndownService() var markdown = turndownService.turndown('

Hello world!

') ``` ### Converting DOM Nodes Turndown also accepts DOM nodes as input (either element nodes, document nodes, or document fragment nodes): ```js var markdown = turndownService.turndown(document.getElementById('content')) ``` ``` -------------------------------- ### Initialize Turndown Service Source: https://github.com/mixmark-io/turndown/wiki/Migrating-from-to-markdown-to-Turndown Use the constructor pattern for Turndown, similar to other modern JavaScript libraries. Requires Node.js. ```javascript var TurndownService = require('turndown') // for Node.js var turndownService = new TurndownService(options) var md = turndownService.turndown(stringOfHTML) ``` -------------------------------- ### Configuration Options Source: https://github.com/mixmark-io/turndown/blob/master/README.md Details the available options for customizing the Turndown conversion process, including standard and advanced settings. ```APIDOC ## Options Options can be passed in to the constructor on instantiation. For example: ```js var turndownService = new TurndownService({ option: 'value' }) ``` ### Standard Options | Option | Valid values | Default | Description | | :-------------------- | :------------ | :------ | :---------- | | `headingStyle` | `setext` or `atx` | `setext` | Style for headings | | `hr` | Any [Thematic break](http://spec.commonmark.org/0.27/#thematic-breaks) | `* * *` | Horizontal rule character | | `bulletListMarker` | `-`, `+`, or `*` | `*` | Marker for bullet lists | | `codeBlockStyle` | `indented` or `fenced` | `indented` | Style for code blocks | | `fence` | ` ``` ` or `~~~` | ` ``` ` | Character for fenced code blocks | | `emDelimiter` | `_` or `*` | `_` | Delimiter for emphasis (italics) | | `strongDelimiter` | `**` or `__` | `**` | Delimiter for strong emphasis (bold) | | `linkStyle` | `inlined` or `referenced` | `inlined` | Style for links | | `linkReferenceStyle` | `full`, `collapsed`, or `shortcut` | `full` | Style for link references | | `preformattedCode` | `false` or [`true`](https://github.com/lucthev/collapse-whitespace/issues/16) | `false` | Whether to preserve whitespace in preformatted code | ### Advanced Options | Option | Valid values | Default | Description | | :-------------------- | :------------ | :------ | :---------- | | `blankReplacement` | rule replacement function | See **Special Rules** below | Replacement for blank lines | | `keepReplacement` | rule replacement function | See **Special Rules** below | Replacement for elements to be kept | | `defaultReplacement` | rule replacement function | See **Special Rules** below | Default replacement for unknown elements | ``` -------------------------------- ### Instantiate TurndownService Source: https://context7.com/mixmark-io/turndown/llms.txt Create a new TurndownService instance. Options can be provided to customize Markdown output, such as heading styles, list markers, code block formatting, and link styles. ```javascript // Node.js var TurndownService = require('turndown') // Basic instantiation with default options var turndownService = new TurndownService() // Instantiation with custom options var turndownService = new TurndownService({ headingStyle: 'atx', // 'setext' (default) or 'atx' hr: '---', // Thematic break style (default: '* * *') bulletListMarker: '-', // '-', '+', or '*' (default: '*') codeBlockStyle: 'fenced', // 'indented' (default) or 'fenced' fence: '```', // '```' (default) or '~~~' emDelimiter: '*', // '_' (default) or '*' strongDelimiter: '__', // '**' (default) or '__' linkStyle: 'referenced', // 'inlined' (default) or 'referenced' linkReferenceStyle: 'full', // 'full' (default), 'collapsed', or 'shortcut' preformattedCode: false // Handle preformatted code (default: false) }) ``` -------------------------------- ### TurndownService Constructor Source: https://context7.com/mixmark-io/turndown/llms.txt Initializes a new TurndownService instance with optional configuration options to customize Markdown output. ```APIDOC ## TurndownService Constructor Creates a new TurndownService instance with optional configuration for controlling Markdown output format, heading styles, list markers, code block formatting, and link styles. ### Method `new TurndownService(options)` ### Parameters #### Request Body (Options Object) - **headingStyle** (string) - Optional - 'setext' (default) or 'atx' - **hr** (string) - Optional - Thematic break style (default: '* * *') - **bulletListMarker** (string) - Optional - '-', '+', or '*' (default: '*') - **codeBlockStyle** (string) - Optional - 'indented' (default) or 'fenced' - **fence** (string) - Optional - '```' (default) or '~~~' - **emDelimiter** (string) - Optional - '_' (default) or '*' - **strongDelimiter** (string) - Optional - '**' (default) or '__' - **linkStyle** (string) - Optional - 'inlined' (default) or 'referenced' - **linkReferenceStyle** (string) - Optional - 'full' (default), 'collapsed', or 'shortcut' - **preformattedCode** (boolean) - Optional - Handle preformatted code (default: false) ### Request Example ```javascript // Basic instantiation with default options var turndownService = new TurndownService() // Instantiation with custom options var turndownService = new TurndownService({ headingStyle: 'atx', hr: '--- ', bulletListMarker: '-', codeBlockStyle: 'fenced', fence: '```', emDelimiter: '*', strongDelimiter: '__', linkStyle: 'referenced', linkReferenceStyle: 'full', preformattedCode: false }) ``` ### Response - **TurndownService instance** - An instance of TurndownService ready for conversion. ``` -------------------------------- ### Interactive Turndown Demo with Options Source: https://github.com/mixmark-io/turndown/blob/master/index.html This JavaScript code powers an interactive demo. It sets up event listeners to update the Markdown output in real-time as the HTML input or selected options change. The `options()` function collects current settings from select elements. ```javascript ;(function () { var input = document.getElementById('input') var output = document.getElementById('output') var optionsForm = document.getElementById('options') var turndownService = new window.TurndownService(options()) input.addEventListener('input', update) optionsForm.addEventListener('change', function () { turndownService = new window.TurndownService(options()) update() }) update() function update () { output.value = turndownService.turndown(input.value) } function options () { var opts = {} var inputs = optionsForm.getElementsByTagName('select') for (var i = 0; i < inputs.length; i++) { var input = inputs[i] opts[input.name] = input.value } return opts } })() ``` -------------------------------- ### Integrate plugins with Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Use the `use` method to integrate plugins, such as `turndown-plugin-gfm`, to extend Turndown's functionality. Plugins can add rules, modify options, or extend behavior. You can use pre-built plugins or create custom ones. ```javascript var TurndownService = require('turndown') // Using turndown-plugin-gfm for GitHub Flavored Markdown var turndownPluginGfm = require('turndown-plugin-gfm') var gfm = turndownPluginGfm.gfm var tables = turndownPluginGfm.tables var strikethrough = turndownPluginGfm.strikethrough var taskListItems = turndownPluginGfm.taskListItems var turndownService = new TurndownService() // Use the full GFM plugin turndownService.use(gfm) // Or use specific plugins turndownService.use([tables, strikethrough, taskListItems]) // Convert GFM content var html = ""
NameValue
Alpha1
" console.log(turndownService.turndown(html)) ``` ```javascript // Create a custom plugin function myPlugin(turndownService) { turndownService.addRule('highlight', { filter: 'mark', replacement: function (content) { return '==' + content + '==' } }) turndownService.keep(['details', 'summary']) } turndownService.use(myPlugin) // Plugins can be chained turndownService .use(tables) .use(strikethrough) .use(myPlugin) ``` -------------------------------- ### Methods Source: https://github.com/mixmark-io/turndown/blob/master/README.md Documentation for the core methods available on the TurndownService instance, including `addRule`, `keep`, and `remove`. ```APIDOC ## Methods ### `addRule(key, rule)` The `key` parameter is a unique name for the rule for easy reference. Example: ```js turndownService.addRule('strikethrough', { filter: ['del', 's', 'strike'], replacement: function (content) { return '~' + content + '~' } }) ``` `addRule` returns the `TurndownService` instance for chaining. See **Extending with Rules** below. ### `keep(filter)` Determines which elements are to be kept and rendered as HTML. By default, Turndown does not keep any elements. The filter parameter works like a rule filter (see section on filters belows). Example: ```js turndownService.keep(['del', 'ins']) turndownService.turndown('

Hello worldWorld

') // 'Hello worldWorld' ``` This will render `` and `` elements as HTML when converted. `keep` can be called multiple times, with the newly added keep filters taking precedence over older ones. Keep filters will be overridden by the standard CommonMark rules and any added rules. To keep elements that are normally handled by those rules, add a rule with the desired behaviour. `keep` returns the `TurndownService` instance for chaining. ### `remove(filter)` Determines which elements are to be removed altogether i.e. converted to an empty string. By default, Turndown does not remove any elements. The filter parameter works like a rule filter (see section on filters belows). Example: ```js turndownService.remove('del') turndownService.turndown('

Hello worldWorld

') // 'Hello World' ``` This will remove `` elements (and contents). `remove` can be called multiple times, with the newly added remove filters taking precedence over older ones. Remove filters will be overridden by the keep filters, standard CommonMark rules, and any added rules. To remove elements that are normally handled by those rules, add a rule with the desired behaviour. `remove` returns the `TurndownService` instance for chaining. ``` -------------------------------- ### Basic Turndown Usage in Node.js Source: https://github.com/mixmark-io/turndown/blob/master/README.md Initialize TurndownService and convert an HTML string to Markdown in a Node.js environment. ```javascript // For Node.js var TurndownService = require('turndown') var turndownService = new TurndownService() var markdown = turndownService.turndown('

Hello world!

') ``` -------------------------------- ### Turndown use() Method Source: https://context7.com/mixmark-io/turndown/llms.txt The `use()` method integrates plugins or arrays of plugins to extend TurndownService functionality. Plugins are functions that receive the TurndownService instance and can add rules, modify options, or extend behavior. ```APIDOC ## use(plugin) ### Description Integrates plugins or arrays of plugins to extend TurndownService functionality. Plugins are functions that receive the TurndownService instance and can add rules, modify options, or extend behavior. ### Method `use(plugin)` ### Parameters #### Plugin - **plugin** (function | Array) - Required - A plugin function or an array of plugin functions to be applied. ### Request Example ```javascript var TurndownService = require('turndown') // Using turndown-plugin-gfm for GitHub Flavored Markdown var turndownPluginGfm = require('turndown-plugin-gfm') var gfm = turndownPluginGfm.gfm var tables = turndownPluginGfm.tables var strikethrough = turndownPluginGfm.strikethrough var taskListItems = turndownPluginGfm.taskListItems var turndownService = new TurndownService() // Use the full GFM plugin turndownService.use(gfm) // Or use specific plugins turndownService.use([tables, strikethrough, taskListItems]) // Convert GFM content var html = '
NameValue
Alpha1
  • Done
  • Todo
' console.log(turndownService.turndown(html)) // Create a custom plugin function myPlugin(turndownService) { turndownService.addRule('highlight', { filter: 'mark', replacement: function (content) { return '==' + content + '==' } }) turndownService.keep(['details', 'summary']) } turndownService.use(myPlugin) // Plugins can be chained turndownService .use(tables) .use(strikethrough) .use(myPlugin) ``` ``` -------------------------------- ### Turndown ES Module Usage Source: https://context7.com/mixmark-io/turndown/llms.txt Shows how to import and use Turndown as an ES Module, typically within modern JavaScript projects or build systems. ```html ``` -------------------------------- ### Basic Turndown Conversion Source: https://github.com/mixmark-io/turndown/blob/master/index.html Instantiate TurndownService and convert a simple HTML string to Markdown. Ensure the TurndownService is correctly imported or available in the global scope. ```javascript var turndownService = new TurndownService() console.log( turndownService.turndown('

Hello world

') ) ``` -------------------------------- ### Turndown Browser Usage with CDN Source: https://context7.com/mixmark-io/turndown/llms.txt Demonstrates how to include Turndown via a CDN script tag and use the global TurndownService to convert HTML strings or DOM elements. ```html ``` -------------------------------- ### turndown(input) Source: https://context7.com/mixmark-io/turndown/llms.txt The primary method for converting HTML strings or DOM nodes into Markdown format. ```APIDOC ## turndown(input) The main conversion method that transforms HTML strings or DOM nodes into Markdown. Accepts strings, element nodes, document nodes, or document fragment nodes as input. ### Method `turndownService.turndown(input)` ### Parameters #### Path Parameters - **input** (string | Element | Document | DocumentFragment) - Required - The HTML string or DOM node to convert. ### Request Example ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Convert HTML string to Markdown var markdown = turndownService.turndown('

Hello World

') console.log(markdown) // Convert complex HTML var html = `

Article Title

This is a bold and italic paragraph.

  • First item
  • Second item
const x = 42;
` var turndownServiceWithOptions = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' }) var result = turndownServiceWithOptions.turndown(html) console.log(result) // Convert DOM node (browser environment) // var element = document.getElementById('content') // var markdown = turndownService.turndown(element) ``` ### Response - **string** - The converted Markdown string. ``` -------------------------------- ### Markdown Link Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html A standard Markdown link. Used to create hyperlinks. ```markdown I [need](http://example.com/need) [more](http://www.example.com/more) spaces! ``` ```markdown I [need](http://example.com/need) [more](http://www.example.com/more) spaces! ``` ```markdown Text at root **[link text with trailing space in strong](http://www.example.com)** more text at root ``` ```markdown Text at root **[link text with trailing space in strong](http://www.example.com)** more text at root ``` ```markdown [c[iao](http://www.example.com) ``` ```markdown [c[iao](http://www.example.com) ``` -------------------------------- ### Convert HTML to Markdown Source: https://context7.com/mixmark-io/turndown/llms.txt Use the `turndown` method to convert HTML strings or DOM nodes into Markdown. This method accepts various input types and can be configured with custom rules. ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Convert HTML string to Markdown var markdown = turndownService.turndown('

Hello World

') console.log(markdown) // Output: // Hello World // ========== // Convert complex HTML var html = "

Article Title

This is a bold and italic paragraph.

  • First item
  • Second item
const x = 42;
" var turndownService = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' }) var result = turndownService.turndown(html) console.log(result) // Output: // # Article Title // // This is a **bold** and _italic_ paragraph. // // * First item // * Second item // // ```javascript // const x = 42; // ``` // Convert DOM node (browser environment) var element = document.getElementById('content') var markdown = turndownService.turndown(element) ``` -------------------------------- ### Custom Blank Replacement in Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Configure how Turndown handles elements containing only whitespace. The default behavior differentiates between block and inline elements. ```javascript var TurndownService = require('turndown') // Custom blank replacement - how to handle elements with only whitespace var turndownService = new TurndownService({ blankReplacement: function (content, node) { // Default behavior: block elements get newlines, inline get nothing return node.isBlock ? '\n\n' : '' } }) ``` -------------------------------- ### HTML Link with Brackets Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html An HTML link with square brackets in the text. The brackets are escaped to be treated literally. ```html \[This\] is a sentence with brackets ``` -------------------------------- ### Turndown remove() Method Source: https://context7.com/mixmark-io/turndown/llms.txt The `remove()` method allows you to specify elements that should be completely removed from the output, including their content. These elements will be converted to empty strings. ```APIDOC ## remove(filter) ### Description Specifies elements to completely remove from the output, including their content. The elements will be converted to empty strings. ### Method `remove(filter)` ### Parameters #### Filter - **filter** (string[] | function) - Required - An array of element names (e.g., `['script', 'style']`) or a function that returns `true` for nodes to be removed. ### Request Example ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Remove specific elements entirely turndownService.remove(['script', 'style', 'noscript']) var markdown = turndownService.turndown('

Hello

World

') console.log(markdown) // Output: Hello // // World // Remove elements using a function filter turndownService.remove(function (node) { return node.classList && node.classList.contains('no-export') }) var html = '

Visible content

Hidden content
' var result = turndownService.turndown(html) console.log(result) // Output: Visible content // Remove elements with specific attributes turndownService.remove(function (node) { return node.getAttribute('data-ignore') === 'true' }) ``` ``` -------------------------------- ### Add Custom Strikethrough Rule Source: https://github.com/mixmark-io/turndown/blob/master/README.md Extend Turndown's functionality by adding a custom rule to handle strikethrough elements. ```javascript turndownService.addRule('strikethrough', { filter: ['del', 's', 'strike'], replacement: function (content) { return '~' + content + '~' } }) ``` -------------------------------- ### Add Custom Conversion Rule Source: https://context7.com/mixmark-io/turndown/llms.txt Extend Turndown's functionality by adding custom rules for specific HTML elements. Rules consist of a filter and a replacement function to define how elements are converted to Markdown. ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Add strikethrough support turndownService.addRule('strikethrough', { filter: ['del', 's', 'strike'], replacement: function (content) { return '~~' + content + '~~' } }) var markdown = turndownService.turndown('

This is deleted text

') console.log(markdown) // Output: This is ~~deleted~~ text // Add custom rule with function filter turndownService.addRule('highlightedCode', { filter: function (node, options) { return ( node.nodeName === 'CODE' && node.parentNode.nodeName === 'PRE' && node.classList.contains('highlighted') ) }, replacement: function (content, node, options) { var language = node.getAttribute('data-language') || '' return '\n\n```' + language + '\n' + node.textContent + '\n```\n\n' } }) // Add rule for custom callout boxes turndownService.addRule('callout', { filter: function (node) { return node.nodeName === 'DIV' && node.classList.contains('callout') }, replacement: function (content, node) { var type = node.getAttribute('data-type') || 'note' return '\n\n> **' + type.toUpperCase() + ':** ' + content.trim() + '\n\n' } }) // Rules can be chained turndownService .addRule('subscript', { filter: 'sub', replacement: function (content) { return '~' + content + '~' } }) .addRule('superscript', { filter: 'sup', replacement: function (content) { return '^' + content + '^' } }) ``` -------------------------------- ### addRule(key, rule) Source: https://context7.com/mixmark-io/turndown/llms.txt Adds a custom conversion rule to the TurndownService for handling specific HTML elements or patterns. ```APIDOC ## addRule(key, rule) Adds a custom conversion rule for specific HTML elements. Rules consist of a filter (string, array, or function) and a replacement function that returns the Markdown output. ### Method `turndownService.addRule(key, rule)` ### Parameters #### Path Parameters - **key** (string) - Required - A unique identifier for the rule. - **rule** (object) - Required - An object containing the filter and replacement function. - **filter** (string | Array | Function) - Required - Specifies which nodes the rule applies to. Can be an element name, an array of names, or a function that returns true for matching nodes. - **replacement** (Function) - Required - A function that takes `(content, node, options)` and returns the Markdown string for the matched element. ### Request Example ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Add strikethrough support turndownService.addRule('strikethrough', { filter: ['del', 's', 'strike'], replacement: function (content) { return '~~' + content + '~~' } }) var markdown = turndownService.turndown('

This is deleted text

') console.log(markdown) // Add custom rule with function filter turndownService.addRule('highlightedCode', { filter: function (node, options) { return ( node.nodeName === 'CODE' && node.parentNode.nodeName === 'PRE' && node.classList.contains('highlighted') ) }, replacement: function (content, node, options) { var language = node.getAttribute('data-language') || '' return '\n\n```' + language + '\n' + node.textContent + '\n```\n\n' } }) // Add rule for custom callout boxes turndownService.addRule('callout', { filter: function (node) { return node.nodeName === 'DIV' && node.classList.contains('callout') }, replacement: function (content, node) { var type = node.getAttribute('data-type') || 'note' return '\n\n> **' + type.toUpperCase() + ':** ' + content.trim() + '\n\n' } }) // Rules can be chained turndownService .addRule('subscript', { filter: 'sub', replacement: function (content) { return '~' + content + '~' } }) .addRule('superscript', { filter: 'sup', replacement: function (content) { return '^' + content + '^' } }) ``` ### Response - **TurndownService instance** - The TurndownService instance with the new rule added, allowing for method chaining. ``` -------------------------------- ### Turndown Usage with DOM Nodes Source: https://github.com/mixmark-io/turndown/blob/master/README.md Convert HTML content directly from a DOM element into Markdown. ```javascript var markdown = turndownService.turndown(document.getElementById('content')) ``` -------------------------------- ### Keep HTML elements with Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Use the `keep` method to specify elements that should be preserved as raw HTML. This is useful for elements without a direct Markdown equivalent. You can provide an array of tag names or a function filter. ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Keep specific elements as HTML turndownService.keep(['del', 'ins', 'mark']) var markdown = turndownService.turndown( '

Hello world universe

' ) console.log(markdown) // Output: Hello world universe ``` ```javascript // Keep elements using a function filter turndownService.keep(function (node) { return node.nodeName === 'DIV' && node.classList.contains('keep-html') }) var html = '
Preserved
Converted
' var result = turndownService.turndown(html) console.log(result) // Output:
Preserved
// // Converted ``` ```javascript // Chaining keep calls turndownService .keep(['iframe', 'video']) .keep(['audio', 'canvas']) ``` -------------------------------- ### Markdown Unordered List Item Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html A Markdown unordered list item. Used for bulleted lists. ```markdown * Indented li with leading/trailing newlines ``` ```markdown * li without whitespace ``` ```markdown * An unordered list item ``` ```markdown - An unordered list item ``` ```markdown + An unordered list item ``` -------------------------------- ### Overriding `escape` Source: https://github.com/mixmark-io/turndown/blob/master/README.md Details how to customize the Markdown escaping behavior by overriding the `TurndownService.prototype.escape` method. ```APIDOC ## Overriding `TurndownService.prototype.escape` ### Description Customize the Markdown escaping behavior by overriding `TurndownService.prototype.escape`. This method takes the text of each HTML element and should return a version with Markdown characters escaped. ### Method Signature `escape(text)` ### Parameters - **text** (string) - The text content of an HTML element. ### Returns - **string**: The text with Markdown characters escaped. ### Note Text within `` elements is never passed to the `escape` method. ``` -------------------------------- ### Remove HTML elements with Turndown Source: https://context7.com/mixmark-io/turndown/llms.txt Use the `remove` method to specify elements that should be completely removed from the output, including their content. This is useful for elements like scripts or styles. You can provide an array of tag names or a function filter. ```javascript var TurndownService = require('turndown') var turndownService = new TurndownService() // Remove specific elements entirely turndownService.remove(['script', 'style', 'noscript']) var markdown = turndownService.turndown( '

Hello

World

' ) console.log(markdown) // Output: Hello // // World ``` ```javascript // Remove elements using a function filter turndownService.remove(function (node) { return node.classList && node.classList.contains('no-export') }) var html = '

Visible content

Hidden content
' var result = turndownService.turndown(html) console.log(result) // Output: Visible content ``` ```javascript // Remove elements with specific attributes turndownService.remove(function (node) { return node.getAttribute('data-ignore') === 'true' }) ``` -------------------------------- ### Markdown Numbered List Item Source: https://github.com/mixmark-io/turndown/blob/master/test/index.html A Markdown numbered list item. Used for ordered lists. ```markdown 1. Chapter One ``` ```markdown 1. Chapter One ``` ```markdown 1. First ``` ```markdown 1. First ```