QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Truncate

Verified

Shortens text to a maximum length with a suffix, optionally on a word boundary.

  • string
  • truncate
  • mask
  • hide
  • text

Install

npx shadcn@latest add https://quicksnip.dev/r/truncate.json

Code

/**
 * Shortens text to at most `maxLength` characters (including the suffix).
 * With `wordBoundary`, it avoids cutting words in half.
 */
export function truncate(
  text: string,
  maxLength: number,
  { suffix = "…", wordBoundary = false }: { suffix?: string; wordBoundary?: boolean } = {},
): string {
  if (text.length <= maxLength) return text;
  let cut = text.slice(0, Math.max(0, maxLength - suffix.length));
  if (wordBoundary) {
    const lastSpace = cut.lastIndexOf(" ");
    if (lastSpace > 0) cut = cut.slice(0, lastSpace);
  }
  return cut.trimEnd() + suffix;
}

Usage

truncate("The quick brown fox", 10);                         // "The quick…"
truncate("The quick brown fox", 12, { wordBoundary: true }); // "The quick…"