truncate

import { truncate } from "jsr:@ende/text";

function

function truncate(str: string, maxLength: number, options?: TruncateOptions): string

Truncates a string to at most maxLength UTF-16 code units. When truncation occurs the suffix is included within the maxLength budget. Surrogate pairs are never split, so the result may be shorter than maxLength when a cut would land inside a pair. When the suffix itself contains surrogate pairs and maxLength is very small, the result can even be empty.

Note: this function is not grapheme-cluster-aware. Combining characters, flag emoji, and ZWJ sequences may still be visually split.

str: string

The string to truncate.

maxLength: number

The maximum length of the returned string (must be a non-negative integer).

options?: TruncateOptions

The truncation options.

Returns

The truncated string.

Example: End truncation (default)

import { truncate } from "@ende/text/truncate";
import { assertEquals } from "@ende/assert";

assertEquals(truncate("Hello, world!", 8), "Hello, …");
assertEquals(truncate("Short", 10), "Short");

Example: Middle truncation

import { truncate } from "@ende/text/truncate";
import { assertEquals } from "@ende/assert";

assertEquals(
  truncate("src/components/Button.tsx", 18, { position: "middle" }),
  "src/comp…utton.tsx",
);

Example: Start truncation

import { truncate } from "@ende/text/truncate";
import { assertEquals } from "@ende/assert";

assertEquals(
  truncate("Hello, world!", 8, { position: "start" }),
  "… world!",
);

Example: Custom suffix

import { truncate } from "@ende/text/truncate";
import { assertEquals } from "@ende/assert";

assertEquals(
  truncate("Hello, world!", 10, { suffix: "→" }),
  "Hello, wo→",
);

Source