Technical skill practice

JavaScript String Length: Code Units, Code Points and Graphemes

JavaScript string length counts UTF-16 code units. That can differ from the number of code points or user-perceived characters. Name the unit before imposing a limit or displaying a character count.

The task

Measure a decomposed accented letter followed by an emoji. Use an explicit English grapheme segmenter for the third count and inspect the runtime results.

Runnable Node 22 example

const assert = require('node:assert/strict');

const text = 'e\u0301🙂';
const points = [...text];
const graphemes = [...new Intl.Segmenter('en', {granularity: 'grapheme'}).segment(text)];
assert.equal(text.length, 4);
assert.equal(points.length, 3);
assert.equal(graphemes.length, 2);
assert.deepEqual(points, ['e', '\u0301', '🙂']);
console.log(`units=${text.length}; points=${points.length}; graphemes=${graphemes.length}`);

Expected output and explanation

The e and combining accent each contribute one code unit. The emoji uses two, producing length four. String iteration keeps the emoji together as one code point but still separates the combining accent, yielding three points.

The grapheme count groups the letter and accent, giving two segments for this fixture. That is a different question from storage length. This exact example ran on Node22; segmentation behavior depends on the Unicode and internationalization data available in the runtime.

Output from the example

units=4; points=3; graphemes=2

Pitfall to check

Do not label length as a universal count of visible characters. A database limit, protocol limit and user-facing text limit may each use different units. Test representative language and emoji cases against the chosen requirement.

Questions, answered

Does Array.from(text) solve every character-counting need?

It counts code points through string iteration, not grapheme clusters. The combining-accent example demonstrates why those can still differ.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.