Toolbox-XToolbox-X

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): string

Parameters

  • html (unknown): The HTML content to parse. Non-string inputs are converted to strings, and null/undefined values return an empty string.
  • options (HtmlToTextOptions, optional): Configuration object to control the parser's behaviour.

Options

OptionTypeDefaultDescription
brToNewLinebooleantrueConverts <br> tags into line breaks (\n).
blockToNewLinebooleantrueInserts newlines before and after block-level HTML tags.
decodeEntitiesbooleantrueDecodes common, decimal, and hexadecimal HTML entities.
removeScriptsbooleantrueRemoves <script> tags and their inner content.
removeStylesbooleantrueRemoves <style> tags and their inner content.
preservePreAndCodebooleanfalsePreserves formatting inside <pre> and <code> elements.
listMarkerstring | ListMarkers'- 'Prefix indicator for list items (<li>).
tableCellSeparatorstring'\t'Separator between table cells.
blockSeparatorstring'\n'Separator between adjacent block-level elements.
normalizeWhitespacebooleantrueCollapses redundant spaces, tabs, and duplicate lines.
maxBlankLinesnumber2Max consecutive blank lines allowed in output.
trimOutputbooleantrueTrims leading and trailing whitespace from output.

Note

  • List Markers: Can be configured globally as a string, or independently per list type (ol or ul) using a config object. The ordered lists counter always increments sequentially starting from 1.
  • Pre & Code Blocks: Spacing inside these tags is preserved exactly as written when preservePreAndCode is set to true.

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

Last updated: Thu, Jul 16, 2026 09:17:49AM (UTC)

On this page