Truncate visible characters with Intl.Segmenter
Use Intl.Segmenter to shorten JavaScript strings at grapheme boundaries so accents and joined emoji stay intact.
You shorten a profile label to fit a card. After slicing, an accented letter loses its accent or an emoji turns into part of a different one. The place you cut the string depends on what you count as a character.
Find the boundaries before you slice
JavaScript string offsets count UTF-16 code units. The spread operator offers a different unit: it iterates Unicode code points. A combining accent is a code point of its own. A joined emoji can span several code points.
const text = "e\u0301👩💻!"
console.log(text.length) // 8
console.log([...text].length) // 6
console.log(text.slice(0, 1)) // e
console.log([...text].slice(0, 3).join("")) // é👩The first slice loses the accent and the second slice keeps the accent but cuts the joined emoji.
A grapheme cluster is a unit a reader can perceive as one character. In this string, the first cluster is e plus its accent, and the second is the woman technologist emoji. The exclamation mark is the third cluster.
diagram
Three ways to count the label
Cut at the next grapheme’s start
An Intl.Segmenter with grapheme granularity gives you an iterable of segment records. Each record has an index in UTF-16 code units, so you can pass it straight to slice. Walk the string until you find the first cluster you plan to omit.
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" })
export function truncate(text, limit) {
if (!Number.isSafeInteger(limit) || limit < 0) {
throw new RangeError("limit must be a nonnegative integer")
}
let kept = 0
for (const { index } of graphemes.segment(text)) {
if (kept === limit) return text.slice(0, index) + "…"
kept++
}
return text
}
console.log(truncate("e\u0301👩💻!", 2)) // é👩💻…You get two intact clusters and an ellipsis, with the exclamation mark left out.
Here the limit counts clusters from the original string. The ellipsis is extra, and a string that fits gets no ellipsis. If your limit applies to the display text, reserve a slot for the ellipsis when you detect a cut. A grapheme count does not tell you how wide the text will look. Use CSS overflow rules if you need the label to fit a fixed-width card.