Syntax
Description
Escapes Markdown syntax characters in a string by adding backslashes. This ensures that special characters are not interpreted as Markdown when the output is compiled back to HTML. The method is used internally during conversion but can also be called directly.Parameters
The string containing text that may have Markdown syntax characters
Returns
A string with Markdown syntax characters escaped using backslashes
Escaped Characters
The following patterns are escaped:| Pattern | Escaped As | Example |
|---|---|---|
\ | \\ | foo\bar → foo\\bar |
* | \* | foo*bar → foo\*bar |
^- (line start) | \- | -foo → \-foo |
^+ (line start) | \+ | + foo → \+ foo |
^=+ (line start) | \= | === → \=== |
^#{1,6} (line start) | \# | ## foo → \## foo |
` | \` | foo`bar → foo\`bar |
^~~~ (line start) | \~~~ | ~~~foo → \~~~foo |
[ | \[ | foo[bar] → foo\[bar] |
] | \] | foo[bar] → foo\[bar\] |
^> (line start) | \> | >quote → \>quote |
_ | \_ | foo_bar → foo\_bar |
^\d+. (line start) | \d+\. | 1. item → 1\. item |
Examples
Basic Escaping
Escape Multiple Characters
Escape Heading Markers
Escape List Markers
Escape Backslashes
Using in Custom Rules
Internal Usage
Theescape method is called automatically during conversion for text nodes (but not for code elements):
Customizing Escape Behavior
You can override the escape method to customize escaping behavior:Example: Less Aggressive Escaping
Notes
- Text in code elements is never passed to
escape - The escaping rules are intentionally aggressive to prevent false positives
- Only line-start patterns (like
^-,^>,^#{1,6}) are escaped when at the beginning of a line - The method uses an array of regex patterns applied sequentially
- You can override
TurndownService.prototype.escapefor custom escaping behavior - Be careful when customizing: too little escaping may cause parsing issues when converting back to HTML