Overview
A rule is a plain JavaScript object that defines how a specific HTML element should be converted to Markdown. Each rule consists of required and optional properties that control the conversion behavior.Required Properties
Every rule must have two core properties:filter
Determines which HTML elements this rule applies to. Can be a string, array, or function. See Filters for detailed documentation.replacement
A function that converts the matched HTML element to Markdown. See Replacements for detailed documentation.Optional Properties
append
An optional function that outputs content after all nodes have been processed. This is useful for rules that need to collect information during processing and output it at the end. Returns:string - Content to append to the end of the Markdown output
Example from referenceLink rule:
references
An optional array property used to store reference-style links collected during conversion. Used in conjunction with theappend function.
Example from referenceLink rule:
Complete Rule Examples
Simple Rule: Paragraph
The simplest form of a rule with string filter:Array Filter: Heading
A rule that matches multiple element types:Function Filter: Fenced Code Block
A rule with conditional logic based on options:Rule Precedence
When converting HTML, Turndown evaluates rules in the following order and uses the first matching rule:- Blank rule - Handles elements containing only whitespace (except
<a>,<td>,<th>, and void elements) - Added rules - Custom rules added via
addRule() - CommonMark rules - Built-in rules for standard Markdown elements
- Keep rules - Elements to preserve as HTML (via
keep()) - Remove rules - Elements to remove entirely (via
remove()) - Default rule - Fallback for unmatched elements (outputs text content)
- Custom rules can override built-in behavior
- The blank rule always takes precedence to handle empty elements consistently
- There’s always a fallback (default rule) for unrecognized elements
Usage with addRule
Rules are added to a TurndownService instance using theaddRule() method: