A caption preview should not cut a visible character in half. JavaScript string indexes count UTF-16 code units, and spreading a string splits it into code points. Neither operation alone gives you grapheme clusters. Use Intl.Segmenter to choose safe boundaries, then use ordinary slice with an index supplied by the segmenter.
Prerequisites and example
Use a Node.js release with Intl.Segmenter and save the example as UTF-8 in caption.mjs. There are no dependencies. The display rule counts the ellipsis as one cluster and emits it only when the input exceeds the limit. A zero limit displays nothing.
import assert from 'node:assert/strict';
const segmenter = new Intl.Segmenter('en', {granularity: 'grapheme'});
function caption(text, limit) {
if (!Number.isSafeInteger(limit) || limit < 0) throw new RangeError('limit');
if (typeof text !== 'string') throw new TypeError('text');
if (limit === 0) return '';
let n = 0;
let cut = 0;
for (const {index} of segmenter.segment(text)) {
if (n === limit) return text.slice(0, cut) + '…';
if (n === limit - 1) cut = index;
n++;
}
return text;
}
const sample = 'e\u0301👩💻ok';
assert.equal(caption(sample, 3), 'e\u0301👩💻…');
assert.equal(caption(sample, 4), sample);
assert.equal(caption(sample, 1), '…');
assert.equal(caption(sample, 0), '');
assert.equal(caption('', 2), '');
assert.equal(caption('🇸🇬xy', 2), '🇸🇬…');
assert.throws(() => caption(sample, 1.5), RangeError);
console.log(caption(sample, 3));
Run the fixture
node caption.mjs
é👩💻…
The first cluster is an e followed by a combining accent, and the second is an emoji sequence with a joiner. The script records the start of the cluster that would be replaced by the ellipsis. It waits for one further cluster before deciding to truncate. That lookahead makes an exact fit return unchanged. It also avoids constructing an array containing every cluster in a long caption.
Make the UI contract explicit
At a limit of one, an overlong string becomes only the ellipsis under this policy. If your product instead shows one original cluster followed by an ellipsis, write that as a separate contract and change the boundary tests. Grapheme counts are not byte counts, terminal columns, or rendered pixel widths. If the aim is to fit a card at a particular viewport size, use layout measurements or CSS overflow behavior instead of assuming every cluster takes the same space. If you deploy in a runtime where Intl.Segmenter is missing, test a segmentation-capable alternative rather than silently falling back to code units and changing the result for some users.
ECMA-402 Intl.Segmenter and segment index specification · Java Samples Javascript tutorials