Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

truncate

Truncates a string to the specified maximum length and appends an ellipsis (...).

TypeScript
Copied!
1/**
2 * Truncates a string to the specified maximum length and appends an ellipsis (…).
3 *
4 * @param str - The string to truncate.
5 * @param maxLength - The maximum allowed length including ellipsis.
6 * @param ellipsis - Optional string to append (defaults to '...').
7 * @returns Truncated string with ellipsis if it exceeded the limit.
8 */
9export function truncate(str: string, maxLength: number, ellipsis: string = '...'): string {
10  if (maxLength < 0) {
11    throw new Error('maxLength must be non-negative');
12  }
13
14  if (str.length <= maxLength) return str;
15  if (maxLength <= ellipsis.length) return ellipsis.slice(0, maxLength);
16
17  return str.slice(0, maxLength - ellipsis.length) + ellipsis;
18}
  • Customizable Ellipsis

    Supports any trailing string (e.g., "…", "...", or " [truncated]"), making it adaptable to different display needs.

  • Edge-Case Safe

    Gracefully handles very small maxLength values and avoids negative index slicing.

  • Robust Input Validation

    Validates maxLength to prevent misuse or unexpected behavior.

  • Non-Destructive

    Returns the original string if it fits within the length constraint, ensuring no unnecessary processing.

Tests | Examples

TypeScript
Copied!
1test('truncate - shorter string remains unchanged', () => {
2  expect(truncate('Hello', 10)).toBe('Hello');
3});
4
5test('truncate - string exactly at maxLength remains unchanged', () => {
6  expect(truncate('Hello', 5)).toBe('Hello');
7});
8
9test('truncate - longer string gets truncated with default ellipsis', () => {
10  expect(truncate('Hello, world!', 8)).toBe('Hello...');
11});
12
13test('truncate - custom ellipsis', () => {
14  expect(truncate('abcdefg', 6, '!!')).toBe('abcd!!');
15});
16
17test('truncate - maxLength smaller than ellipsis', () => {
18  expect(truncate('abcdefg', 2, '...')).toBe('..');
19});
20
21test('truncate - empty string input', () => {
22  expect(truncate('', 5)).toBe('');
23});
24
25test('truncate - zero length', () => {
26  expect(truncate('abcdefg', 0)).toBe('');
27});
28
29test('truncate - negative length throws', () => {
30  expect(() => truncate('abc', -1)).toThrow('maxLength must be non-negative');
31});

Common Use Cases

  • UI/UX Text Snippets

    Shorten long titles, descriptions, or messages in cards, modals, or lists.

  • Search Result Previews

    Display a portion of matching content with ellipsis to keep layout consistent.

  • Notifications or Alerts

    Limit text length in compact spaces while still indicating there's more content.

  • Mobile Responsiveness

    Truncate content on smaller screens to maintain readability and alignment.

  • Data Export or Logging

    Abbreviate large strings before writing them to logs or files with constrained formats.

Codebase: Utilities -> Strings -> truncate | Yevhen Klymentiev