Sub topic 8
Strings, Emoji and Code Points
This chapter assumes you know how for...of walks the values of an iterable and that strings are one of the built-in iterables. It also helps to know that JavaScript stores strings as sequences of 16-bit units.
Two ways to count a string
JavaScript strings are encoded in UTF-16. Each slot in the string is a code unit, which is 16 bits wide. Most common characters fit in one code unit. Characters outside the Basic Multilingual Plane, such as most emoji, need two code units called a surrogate pair.
The string iterator does not hand out code units. It hands out code points, which are the actual Unicode characters. Each surrogate pair is joined back into one value.
for (const ch of 'a😀') {
console.log(ch);
}
// a
// 😀
console.log('a😀'.length); // 3The length property counts code units, so the result is 3. The loop runs only twice.
The classic loop splits emoji
Indexing with str[i] works on code units. A counter-based loop therefore breaks the emoji into two lone surrogates, and neither one is a valid character by itself.
const s = 'a😀';
for (let i = 0; i < s.length; i++) {
console.log(i, s.charCodeAt(i).toString(16));
}
// 0 '61'
// 1 'd83d'
// 2 'de00'
for (const ch of s) {
console.log(ch, ch.codePointAt(0).toString(16));
}
// a 61
// 😀 1f600Spread syntax and Array.from use the same string iterator, so [...s].length gives 2. This is a quick way to count code points.
Code points are not always what users see
One visible character, which Unicode calls a grapheme cluster, can be made of several code points. Examples are an emoji with a skin-tone modifier, a flag, or a letter followed by a combining accent. for...of yields each of those code points separately.
const text = '👍🏽e\u0301'; // thumbs up + skin tone, e + combining acute
console.log(text.length); // 6 code units
console.log([...text].length); // 4 code points
const seg = new Intl.Segmenter('en', { granularity: 'grapheme' });
for (const { segment } of seg.segment(text)) {
console.log(segment);
}
// 👍🏽
// éThe object returned by Intl.Segmenter.prototype.segment() is iterable too. Each value it yields is an object with a segment property, and the code above pulls that property out with destructuring.
| Approach | Unit it yields | Count for `'👍🏽e\u0301'` |
|---|---|---|
| `str.length` / `str[i]` | UTF-16 code unit | 6 |
| `for...of` / `[...str]` | Code point | 4 |
| `Intl.Segmenter` (grapheme) | Grapheme cluster | 2 |
Use for...of when you need correct Unicode characters, for example when you check code point ranges. Use Intl.Segmenter when the result is shown to people, for example when you count characters for a text limit or truncate a string.
Exercise
What do '🇫🇷'.length, [...'🇫🇷'].length, and the number of for...of iterations over '🇫🇷' evaluate to, and why?
Show answer
length is 4, [...'🇫🇷'].length is 2, and the loop runs twice. The flag is made of two regional-indicator code points, U+1F1EB and U+1F1F7, and each one is a surrogate pair. That gives 4 code units and 2 code points. for...of yields code points, so you get two separate regional-indicator letters. Only a grapheme segmenter returns the flag as one item.
Exercise
Write a function firstChars(str, n) that returns the first n code points of a string without splitting surrogate pairs.
Show answer
const firstChars = (str, n) => [...str].slice(0, n).join(''); Spreading the string goes through the string iterator, which yields whole code points. For example, firstChars('😀😀x', 2) returns '😀😀', while '😀😀x'.slice(0, 2) returns only '😀'.