Skip to content
VersionSize

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.

Implementation

View Source Code
ts
import { assert } from '../function/assert';

/**
 * 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, 3, true); // 'Hello…'
 * truncate(text, 5, true, '...'); // 'Hello...'
 * ```
 *
 * @param str - The string to truncate.
 * @param limit - The maximum string length.
 * @param completeWords - If true, the string is truncated to the nearest word, instead of character.
 * @param ellipsis - The characters to end the truncated string with.
 *
 * @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 = '…'): 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;
  }

  const _limit = completeWords ? str.substring(0, limit).lastIndexOf(' ') : limit;
  const effectiveLimit = _limit > 0 ? _limit : limit;

  return `${str.substring(0, effectiveLimit).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 length provided is less than or equal to the length of the suffix, 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