Trending

World technology news

→
A family emoji and a dotted I shown within grapheme boundaries
Software Engineering · 2026
Software Engineering

Build a Unicode-safe title preview with Intl.Segmenter

Trim long titles by grapheme boundaries and keep emoji sequences, flags, and combining marks intact with a tested Node.js example.

Developer's JournalPublished: Dec 6, 20266 min read
Reading progress0%
In this article
  1. Choose a unit for the preview
  2. Cut at an offset from the original string
  3. Run the example and compare results
  4. Keep the source text for other uses
  5. Test actual layout in the browser
  6. Keep a small production fixture set
  7. Count completed input in a form

Choose a unit for the preview

The first test for a two-character comment preview is often written in ASCII. Real titles can begin with a family emoji or with a letter followed by a combining mark. JavaScript reports string length in UTF-16 code units. Spread syntax iterates by code point and can still split sequences that readers see as a single character. Use an extended grapheme cluster as the unit of the preview budget. A title that fits comes back intact. A longer title reserves its last slot for the ellipsis glyph. Defining those rules up front lets the counter and the renderer share acceptance tests. Some interfaces also show a storage limit in the same form. Keep that unit visible in the product specification so that the user understands which constraint applies.

Cut at an offset from the original string

Create an Intl.Segmenter once at the component or module boundary. A segment record supplies an offset in the input string. The unit of that offset matches String.prototype.slice, so the original bytes can be encoded from the resulting string later without rebuilding its clusters. The function remembers the beginning of the last cluster in the budget. Seeing one more cluster proves that the input overflows and that the last slot belongs to the ellipsis. With a limit of one, an overflowing string therefore becomes an ellipsis. A zero limit returns an empty string. An invalid limit raises RangeError. This makes configuration errors visible even when a perfectly valid input can produce a blank preview.

Frontend data and event flowConceptual sketch · summary of the article's technical flow
Technical referencesECMA-402 · Intl.Segmenter ↗

Run the example and compare results

Save the example as a UTF-8 module and run it with Node.js. The recorded run used Windows, Node.js v24.19.0, ICU 78.3 and Unicode 17.0. Nine string cases succeeded and a negative value raised the expected error. The family, flag and skin-tone cases each retained one whole emoji before the ellipsis. The starting letter of the decomposed İzmir example kept its combining dot, and the exact-fit Türkiye string was returned intact. The test also counts clusters in each result to verify that the ellipsis fits inside the budget. Capture the runtime versions with the output so a future deployment can explain a segmentation change before blaming the application code.

import assert from 'node:assert/strict';

const graphemeBoundaries = new Intl.Segmenter('tr', { granularity: 'grapheme' });

function preview(text, limit) {
  if (!Number.isSafeInteger(limit) || limit < 0) {
    throw new RangeError('limit must be a non-negative safe integer');
  }
  if (limit === 0) return '';

  let count = 0;
  let cutAt = 0;
  for (const { index } of graphemeBoundaries.segment(text)) {
    if (count === limit - 1) cutAt = index;
    if (count === limit) return text.slice(0, cutAt) + '…';
    count += 1;
  }
  return text;
}

const tests = [
  ['accent', 'e\u0301X', 2, 'e\u0301X'],
  ['family', '👨‍👩‍👧‍👦xy', 2, '👨‍👩‍👧‍👦…'],
  ['flag', '🇹🇷ab', 2, '🇹🇷…'],
  ['combining', 'I\u0307zmir', 3, 'I\u0307z…'],
  ['skin tone', '👍🏽ab', 2, '👍🏽…'],
  ['exact fit', 'Türkiye', 7, 'Türkiye'],
  ['one', 'Türkiye', 1, '…'],
  ['zero', 'Türkiye', 0, ''],
  ['empty', '', 2, ''],
];

const cases = tests.map(([name, input, limit, expected]) => {
  const actual = preview(input, limit);
  assert.equal(actual, expected, name);
  const count = [...graphemeBoundaries.segment(actual)].length;
  assert.ok(count <= limit, name);
  return { name, actual, count };
});
assert.throws(() => preview('Türkiye', -1), RangeError);
console.log(JSON.stringify({ node: process.version, icu: process.versions.icu, unicode: process.versions.unicode, cases, invalidLimit: 'RangeError' }, null, 2));

Keep the source text for other uses

Persist the original title and compute the preview in the presentation layer. Mobile and desktop can have different room, and search or exports may need the complete value. If normalization is part of your comparison policy, define it separately. For example, a lookup key can be normalized without altering the display string that a user submitted. Always obtain an offset from the same input passed to slice. A normalized representation can contain a different number of code units. A transport or storage limit may use UTF-8 bytes, which Node.js can count with Buffer.byteLength. A family emoji fits one grapheme slot and occupies several encoded bytes, so the same budget cannot be applied at both boundaries.

Test actual layout in the browser

A grapheme budget controls the submitted content while CSS handles available space. Fonts, direction and the viewport affect which strings fit in a single line. An emoji sequence can be shaped differently if a fallback font is used. Test the narrowest card with its loaded typefaces and include a long unbroken word and right-to-left text. A detail link may use the full accessible name if the visual title is abbreviated. If the application manages copying, test the copied value as well as the label delivered to the screen reader. Pair the layout checks with the Node.js assertions so a screenshot failure can be diagnosed separately from a broken sequence.

Keep a small production fixture set

Capture representative text from supported languages alongside a few deliberately small limits. Cover an empty string, an exact fit and one cluster over budget. Add combining marks, a flag, a skin-tone modifier and a family sequence as targeted cases. When exact agreement matters across a client and a server, run the fixtures on both and pin compatible runtime versions. Older environments can use a compatible segmenter or a stated browser baseline. A silent fallback to code-point slicing gives readers different outcomes for the same rule. The iterator here stops as soon as the overflow decision is possible. Cap accepted input size independently if the application processes large bodies of untrusted text.

Count completed input in a form

If an input form shows a remaining character count, segment the current value when computing that count. Input method editors can compose a character across several events. Waiting until composition has finished before enforcing a limit reduces the chance of cutting an unfinished edit. Associate the validation message with the input. When both the server and the client enforce the rule, share production examples so pasted text is tested too.

Technical referencesECMA-402 · Intl.Segmenter ↗
850 reads ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.