Skip to main content

Syntax

turndownService.addRule(key, rule)

Description

Adds a custom rule to the TurndownService instance. Rules define how specific HTML elements should be converted to Markdown. Each rule has a unique key and contains a filter to match elements and a replacement function to define the conversion.

Parameters

key
string
required
A unique identifier for the rule. Used for easy reference and debugging.
rule
object
required
The rule object defining how to convert matching elements

Returns

instance
TurndownService
Returns the TurndownService instance for method chaining

Examples

Strikethrough Rule

turndownService.addRule('strikethrough', {
  filter: ['del', 's', 'strike'],
  replacement: function (content) {
    return '~' + content + '~'
  }
})

Highlight Rule

turndownService.addRule('highlight', {
  filter: 'mark',
  replacement: function (content) {
    return '==' + content + '=='
  }
})

Custom Filter Function

turndownService.addRule('customLink', {
  filter: function (node, options) {
    return (
      node.nodeName === 'A' &&
      node.getAttribute('href') &&
      node.getAttribute('href').startsWith('http')
    )
  },
  replacement: function (content, node) {
    return '[' + content + '](' + node.getAttribute('href') + ')'
  }
})

Chaining Multiple Rules

turndownService
  .addRule('strikethrough', {
    filter: ['del', 's'],
    replacement: function (content) {
      return '~~' + content + '~~'
    }
  })
  .addRule('underline', {
    filter: 'u',
    replacement: function (content) {
      return '<u>' + content + '</u>'
    }
  })

Notes

  • Returns the instance to enable method chaining
  • Rules are processed in order of precedence (see Rule Precedence documentation)
  • Custom rules take precedence over CommonMark rules but not over the blank rule
  • Tag names in filters should be lowercase
  • The replacement function receives already-converted content for nested elements

Build docs developers (and LLMs) love