filter and replacement properties.
Rule Structure
Every rule consists of two main parts:Creating Your First Custom Rule
1
Understand the basic structure
Let’s create a rule for converting
<del> elements to strikethrough syntax:2
Test the rule
Now use it to convert HTML:
3
Chain multiple rules
The
addRule method returns the service instance, enabling method chaining:Filter Types
Thefilter property determines which elements a rule applies to. There are three types of filters:
String Filter
Select elements by tag name:Tag names in filters should be lowercase, regardless of their case in the HTML document.
Array Filter
Select multiple element types with a single rule:Function Filter
Use a function for complex matching logic:Replacement Function
The replacement function determines the Markdown output. It receives three parameters:Example: List Items
Here’s how Turndown handles list items fromcommonmark-rules.js:
Example: Blockquotes
A simpler example fromcommonmark-rules.js:
Complete Custom Rule Examples
Highlight/Mark Elements
Custom Div Classes
Abbreviations
Keyboard Input
Rule Precedence
When Turndown processes a node, it iterates through rules in this order:1
Blank rule
Handles blank elements (only whitespace). Overrides all other rules.
2
Added rules
Custom rules added via
addRule(). Processed in the order they were added.3
CommonMark rules
Built-in rules from
commonmark-rules.js for standard Markdown elements.4
Keep rules
Elements to keep as HTML (via
keep() method).5
Remove rules
Elements to remove entirely (via
remove() method).6
Default rule
Fallback rule for unrecognized elements.
Advanced Pattern: Accessing Node Properties
Rules can access any DOM node property:Next Steps
API Reference
Explore the complete API documentation for addRule
GFM Plugin
Learn about the GitHub Flavored Markdown plugin