truncate
The truncate utility shortens a string to a specified length and appends a customizable suffix (like an ellipsis) if the string exceeds that length.
Source Code
View Source Code
ts
import { assert } from '../function/assert';
type TruncateOptions = {
completeWords?: boolean;
ellipsis?: string;
};
/**
* Truncates a string if it is longer than the given maximum string length. The last characters of the truncated string are replaced with the ellipsis sign "…".
*
* @example
* ```ts
* const text = 'Hello World';
* truncate(text, 5); // 'Hello…'
* truncate(text, 8, { completeWords: true }); // 'Hello…'
* truncate(text, 5, { ellipsis: '...' }); // 'Hello...'
* ```
*
* @param str - The string to truncate.
* @param limit - The maximum string length.
* @param options - Options for truncation.
* @param [options.completeWords] - If true, truncate to the nearest word boundary.
* @param [options.ellipsis] - Suffix appended after truncation (default: '…').
*
* @returns The truncated string.
*
* @throws {TypeError} If str is not a string or limit is not a positive number.
*/
export function truncate(
str: string,
limit = 25,
{ completeWords = false, ellipsis = '…' }: TruncateOptions = {},
): string {
assert(typeof str === 'string', 'First argument must be a string', {
args: { str },
type: TypeError,
});
assert(
typeof limit === 'number' && limit >= 0 && Number.isFinite(limit),
'Limit must be a non-negative finite number',
{ args: { limit }, type: TypeError },
);
if (str.length <= limit) {
return str;
}
let end = limit;
if (completeWords) {
const wordEnd = str.substring(0, limit).lastIndexOf(' ');
if (wordEnd > 0) end = wordEnd;
}
return `${str.substring(0, end).trim()}${ellipsis}`;
}Features
- Isomorphic: Works in both Browser and Node.js.
- Configurable: Choose the maximum length and the suffix to append.
- Smart Truncation: Only applies if the string is actually longer than the target length.
API
ts
function truncate(input: string, length: number, suffix?: string): string;Parameters
input: The string to be truncated.length: The maximum allowed length of the resulting string, including the suffix.suffix: The string to append to the end of the truncated result (default:'...').
Returns
- The truncated string if it was longer than
length, otherwise the original string.
Examples
Basic Truncation
ts
import { truncate } from '@vielzeug/toolkit';
const text = 'Vielzeug is a Swiss-army knife for TypeScript developers.';
truncate(text, 20); // 'Vielzeug is a Swi...'Custom Suffix
ts
import { truncate } from '@vielzeug/toolkit';
truncate('Read more about this topic', 15, ' [...]');
// 'Read more [...]'Short Strings
ts
import { truncate } from '@vielzeug/toolkit';
// String is shorter than length, returned as-is
truncate('Hello', 10); // 'Hello'Implementation Notes
- If the
lengthprovided is less than or equal to the length of thesuffix, the behavior may vary depending on the implementation (usually returns just the suffix or a portion of it). - Does not attempt to truncate at word boundaries; it cuts exactly at the specified character count.
See Also
- similarity: Compare two strings for similarity.
- camelCase: Convert strings to camelCase.