truncate()
truncate(
str,options):string
Truncates string if it's longer than the given maximum length.
Parameters
str: string
The string to truncate.
options: TruncateOptions = {}
The options object.
Returns: string
The truncated string.
Since
2.0.0
Also known as
truncate (Lodash, es-toolkit, Remeda, Modern Dash) · ❌ (Radashi, Ramda, Effect, Antfu)
Example
truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'
truncate('hi-diddly-ho there, neighborino', { length: 24 });
// => 'hi-diddly-ho there, n...'
truncate('hi-diddly-ho there, neighborino', {
length: 24,
separator: ' '
});
// => 'hi-diddly-ho there,...'
truncate('hi-diddly-ho there, neighborino', {
length: 24,
separator: /,? +/
});
// => 'hi-diddly-ho there...'
truncate('hi-diddly-ho there, neighborino', {
omission: ' [...]'
});
// => 'hi-diddly-ho there, neig [...]'
How it works?
Truncates string to a maximum length with customizable omission.
Options
| Option | Default | Description |
|---|---|---|
length | 30 | Max string length |
omission | '...' | Truncation indicator |
separator | — | Break at word boundary |
Word Boundary
Without separator, cuts mid-word. With separator, breaks at last occurrence.
Custom Omission
Use Cases
Preview text for content cards 📌
Display short previews of long content in cards or lists. Essential for article listings, product descriptions, or comment previews.
const preview = truncate(article.content, { length: 80 });
// => "TypeScript generics provide a way to create reusable components..."
Word-boundary truncation for readable excerpts 📌
Truncate at word boundaries for more natural reading. Avoids cutting words in half.
truncate(description, { length: 30, separator: ' ' });
// => "The quick brown fox jumps..."
Custom omission for branded experiences
Use custom omission strings for branded "read more" indicators.
truncate(post, { length: 50, omission: '… [voir plus]' });
// => "This is a very long social… [voir plus]"
Truncate file names in a file explorer
Shorten long file names in a file tree or upload list while keeping the extension visible.
const truncateFileName = (name: string, maxLen: number) => {
const ext = name.slice(name.lastIndexOf('.'));
if (name.length <= maxLen) return name;
return truncate(name.slice(0, -ext.length), { length: maxLen - ext.length }) + ext;
};
truncateFileName('my-very-long-document-name-final-v2.pdf', 25);
// => "my-very-long-docum....pdf"
TruncateOptions
Options for the truncate function.
Since
2.0.0
Properties
length?: number
Maximum string length (default: 30).
omission?: string
The string to indicate text is omitted (default: '...').
separator?: string | RegExp
The separator pattern to truncate to.