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. If the string is already within the limit, it is returned unchanged (no ellipsis appended). null and undefined inputs are returned as-is to align with other string helpers.

Available since v2.0.0

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.

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