Truncate Text By Grapheme

Shorten UI text by grapheme clusters so emoji and combining marks stay intact, with an ellipsis budget included.

JavascriptData Integrity

Code

javascriptsnippet
31 lines
const segmenter = typeof Intl.Segmenter === "function"
  ? new Intl.Segmenter(undefined, { granularity: "grapheme" })
  : null;

export function truncateGraphemes(text, maxGraphemes, ellipsis = "\u2026") {
  if (!Number.isInteger(maxGraphemes) || maxGraphemes < 0) {
    throw new RangeError("maxGraphemes must be a non-negative integer");
  }
  const value = String(text);
  const graphemes = segmenter
    ? [...segmenter.segment(value)].map((part) => part.segment)
    : Array.from(value);
  if (graphemes.length <= maxGraphemes) return value;
  if (maxGraphemes === 0) return "";
  const suffix = ellipsis ? ellipsis : "";
  const budget = Math.max(0, maxGraphemes - 1);
  return graphemes.slice(0, budget).join("") + suffix;
}

export function truncateMiddle(text, maxGraphemes, marker = "\u2026") {
  const value = String(text);
  const graphemes = segmenter
    ? [...segmenter.segment(value)].map((part) => part.segment)
    : Array.from(value);
  if (graphemes.length <= maxGraphemes) return value;
  if (maxGraphemes <= 1) return marker;
  const keep = maxGraphemes - 1;
  const head = Math.ceil(keep / 2);
  const tail = Math.floor(keep / 2);
  return graphemes.slice(0, head).join("") + marker + graphemes.slice(-tail).join("");
}

What the code does

Truncate Text By Grapheme keeps everything in the functions truncateGraphemes and truncateMiddle.

RangeError is the guard’s signal — thrown at the branch, before any partial work happens.

Watch out for

  • The guard graphemes.length <= maxGraphemes short-circuits the flow with an early return when its condition holds.

Using it

The main signature reads export function truncateGraphemes(text, maxGraphemes, ellipsis = "\u2026")

The surface worth importing is truncateGraphemes; the helpers around it are private to the snippet.

Key statements

return graphemes.slice(0, head).join("") + marker + graphemes.slice(-tail).join("");
throw new RangeError("maxGraphemes must be a non-negative integer");
? new Intl.Segmenter(undefined, { granularity: "grapheme" })
: null;

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `RangeError` is thrown while the state is still recoverable.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `truncateGraphemes`, `truncateMiddle` at load time.