truncate
EditTruncates text to a maximum grapheme length including its marker.
const segmenter = typeof Intl !== "undefined" && typeof Intl.Segmenter === "function" ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) : undefined;
const splitGraphemes = (value: string): string[] => { if (!segmenter) return Array.from(value); return Array.from(segmenter.segment(value), ({ segment }) => segment);};
/** Truncates text to a maximum grapheme length, including its omission marker. */export const truncate = ( value: string, maxLength: number, omission: string = "…"): string => { if (!Number.isSafeInteger(maxLength) || maxLength < 0) { throw new RangeError("maxLength must be a non-negative safe integer"); }
const graphemes = splitGraphemes(value); if (graphemes.length <= maxLength) return value;
const marker = splitGraphemes(omission); if (marker.length >= maxLength) return marker.slice(0, maxLength).join(""); return graphemes.slice(0, maxLength - marker.length).join("") + omission;};Download
Section titled “Download”wget -O src/lib/truncate.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/truncate.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/truncate.ts" src/lib/truncate.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { truncate } from "./truncate";
const label = truncate("A very long label", 10);// "A very lo…"
const familyLabel = truncate("👨👩👧👦 family account", 10);// "👨👩👧👦 family …"value(string) — Text to shorten.maxLength(number) — Non-negative safe-integer maximum number of visible characters.omission(string) — Marker included within the maximum, defaulting to….- Uses
Intl.Segmenterto preserve emoji sequences, flags, and combining marks. Environments without it fall back to Unicode code points.