@padmaj/truncate
v1.0.1
Published
Truncate strings at word boundaries with a customizable suffix. Zero dependencies. TypeScript-first.
Maintainers
Readme
@padmaj/truncate
Truncate strings at word boundaries with a customizable suffix. Zero dependencies. TypeScript-first. Works in Node and browser.
Install
npm install @padmaj/truncateUsage
import { truncate } from '@padmaj/truncate'
truncate('hello world foo bar', 10) // → 'hello...'
truncate('hello world', 20) // → 'hello world' (no truncation)
truncate('hello world foo', 13, { suffix: ' →' }) // → 'hello world →'
truncate('hello world', 8, { wordBoundary: false }) // → 'hello...'
truncate('hello world', 7, { suffix: '' }) // → 'hello w'API
truncate(input, maxLength, options?)
| Option | Type | Default | Description |
|---|---|---|---|
| suffix | string | '...' | Appended when truncation occurs |
| wordBoundary | boolean | true | Cut at last space instead of mid-word |
Returns a string of at most maxLength characters (including suffix). Throws RangeError if maxLength <= 0.
Behaviour
- If
inputfits withinmaxLength, it is returned unchanged. - With
wordBoundary: true(default), the result is trimmed back to the last space so no word is cut mid-way. - If no space exists and
wordBoundary: true, the string is cut at the character limit. - If
suffixis empty (''), the string is hard-sliced atmaxLengthwith no word boundary applied.
Notes
- The
maxLengthlimit includes the suffix length —truncate('hello world', 10)returns an 8-char string ('hello...') not a 10+3 char string. - Passing
maxLength <= 0,Infinity, orNaNthrows aRangeError.
License
MIT
