Skip to content

truncate

Truncates a string to maxLength characters, appending an ellipsis when cut.

The ellipsis counts toward maxLength, so the result is always at most maxLength characters long. The cut point is snapped back to the nearest grapheme-cluster boundary and trailing breakable whitespace is trimmed, so a cut never leaves a dangling space ('Hello,…', not 'Hello, …') or a split multi-code-unit character (a lone surrogate, an orphaned combining mark, a family emoji cut mid-sequence, …) in front of the ellipsis — this means the result can be shorter than maxLength when the cut point falls on whitespace or inside such a cluster. Non-breaking spaces (U+00A0) and other “no-break” Unicode separators are deliberately left untouched, since their whole purpose is to resist being treated as a break point. If the string is already within the limit, it is returned unchanged (no ellipsis appended, no trimming). null and undefined inputs are returned as-is to align with other string helpers.

This is a mechanical cut at exactly maxLength — it doesn’t know or care about sentence structure. For a card/header-sized summary that prefers to end on a whole sentence when one fits, see excerpt instead.

Available since v2.0.0

import { truncate } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { truncate } from 'helpers4/string';
truncate(input: undefined, maxLength: number, ellipsis?: string): undefined
ParameterTypeDescription
inputundefinedThe string to truncate.
maxLengthnumberMaximum number of characters in the output (including ellipsis).
ellipsisstringAppended when the string is cut. Defaults to `’…’`. (optional)

undefined — The (possibly truncated) string, or the input itself when null/undefined.

Appends … when the string exceeds the limit, trimming a trailing space at the cut point.

truncate('Hello, world!', 8)
// => 'Hello,…'

The ellipsis counts toward the maxLength.

truncate('Hello, world!', 8, '...')
// => 'Hello...'

Returned unchanged when already short enough.

truncate('Hi', 10)
// => 'Hi'

View source on GitHub