HTML to Text
Convert HTML strings into plain text with customizable options.
htmlToText
The htmlToText function converts HTML strings into formatted plain text by stripping HTML tags while preserving line breaks, paragraph structure, lists, tables, and spacing according to customizable rules.
Function Signature
function htmlToText(html: unknown, options?: HtmlToTextOptions): stringParameters
html(unknown): The HTML content to parse. Non-string inputs are converted to strings, andnull/undefinedvalues return an empty string.options(HtmlToTextOptions, optional): Configuration object to control the parser's behaviour.
Options
| Option | Type | Default | Description |
|---|---|---|---|
brToNewLine | boolean | true | Converts <br> tags into line breaks (\n). |
blockToNewLine | boolean | true | Inserts newlines before and after block-level HTML tags. |
decodeEntities | boolean | true | Decodes common, decimal, and hexadecimal HTML entities. |
removeScripts | boolean | true | Removes <script> tags and their inner content. |
removeStyles | boolean | true | Removes <style> tags and their inner content. |
preservePreAndCode | boolean | false | Preserves formatting inside <pre> and <code> elements. |
listMarker | string | ListMarkers | '- ' | Prefix indicator for list items (<li>). |
tableCellSeparator | string | '\t' | Separator between table cells. |
blockSeparator | string | '\n' | Separator between adjacent block-level elements. |
normalizeWhitespace | boolean | true | Collapses redundant spaces, tabs, and duplicate lines. |
maxBlankLines | number | 2 | Max consecutive blank lines allowed in output. |
trimOutput | boolean | true | Trims leading and trailing whitespace from output. |
Note
- List Markers: Can be configured globally as a string, or independently per list type (
olorul) using a config object. The ordered lists counter always increments sequentially starting from1. - Pre & Code Blocks: Spacing inside these tags is preserved exactly as written when
preservePreAndCodeis set totrue.
Sub-Option: ListMarkers
When specifying listMarker as an object, configure ordered and unordered list bullets independently:
ol(string, default:'1. '): Dynamic sequentially incremented prefix.ul(string, default:'- '): Static marker prefix.
Types
interface HtmlToTextOptions {
brToNewLine?: boolean;
blockToNewLine?: boolean;
decodeEntities?: boolean;
removeScripts?: boolean;
removeStyles?: boolean;
preservePreAndCode?: boolean;
listMarker?: string | ListMarkers;
tableCellSeparator?: string;
blockSeparator?: string;
normalizeWhitespace?: boolean;
maxBlankLines?: number;
trimOutput?: boolean;
}
interface ListMarkers {
ol?: string;
ul?: string;
}Example Usage
playground.ts
See Also
- markdownToText — Convert Markdown formatted strings to plain text.
- normalizeString — Clean and normalize string whitespaces.
- trimString — Remove leading, trailing, and duplicate spaces.
Last updated: Thu, Jul 16, 2026 09:17:49AM (UTC)
