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
A unique identifier for the rule. Used for easy reference and debugging.
The rule object defining how to convert matching elements filter
string | array | function
required
Determines which elements this rule applies to:
String : A single tag name (e.g., 'p')
Array : Multiple tag names (e.g., ['em', 'i'])
Function : Custom filter function (node, options) => boolean
Function that returns the Markdown string for the matched element. Signature: (content, node, options) => string
content: The inner content of the element (already converted)
node: The DOM node being converted
options: The TurndownService options object
Function to append content after the main conversion. Signature: (options) => string
Returns
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