Sub topic 8
Strings, Emoji and Code Points
This chapter assumes you already know the basic for...of syntax from the earlier chapters and that strings are iterable. It also helps to know that str[i] and str.length exist. It does not assume you know how Unicode works. The parts you need are explained here.
A string looks like a simple list of characters. JavaScript stores it as a sequence of 16-bit units, though, and that detail decides what each loop hands you. A classic indexed loop and for...of can give different results on the same string, and only one of them keeps emoji intact.
Code units versus code points
Two terms matter here:
- A code point is the number Unicode gives to one symbol.
ais U+0061 and 😀 is U+1F600. - A code unit is one 16-bit chunk of JavaScript's internal UTF-16 storage.
Code points up to U+FFFF fit in one code unit. Larger code points, which include most emoji, need two code units called a surrogate pair. The first unit, called the high surrogate, falls in the range D800–DBFF. The second, the low surrogate, falls in DC00–DFFF. Neither half means anything by itself.
str.length, str[i] and charCodeAt all count code units. The string iterator that for...of uses moves one code point at a time.
Indexed loop versus for...of
Here is the same string walked both ways. The code prints hexadecimal codes so the output is the same in every terminal, since terminals display lone surrogates differently.
const s = 'a😀';
console.log(s.length); // 3
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.length, ch.codePointAt(0).toString(16));
}
// a 1 61
// 😀 2 1f600The indexed loop runs three times. Two of those passes produce half an emoji. The for...of loop runs twice, and the emoji value it yields is itself a string of length 2, because one code point here takes two code units.
Other tools that follow the string iterator
Spread syntax, Array.from and destructuring all consume a string through the same iterator as for...of, so they also split it by code point. split('') splits by code unit.
const s = 'a😀';
console.log([...s].length); // 2
console.log(Array.from(s).length); // 2
console.log(s.split('').length); // 3
const [first, second] = s;
console.log(second === '😀'); // true
// Reversing: split('') tears the surrogate pair apart
const broken = s.split('').reverse().join('');
console.log(broken === '\uDE00\uD83Da'); // true (invalid text)
const fixed = [...s].reverse().join('');
console.log(fixed === '😀a'); // true| Operation | Unit it works in | Result for `'a😀'` |
|---|---|---|
| `s.length` | code units | 3 |
| `s[i]`, `charAt`, `charCodeAt` | code units | 3 positions |
| `s.split('')` | code units | 3 pieces |
| `for...of`, `[...s]`, `Array.from(s)` | code points | 2 values |
| `s.codePointAt(i)` | code point starting at unit index `i` | `0x1f600` at `i = 1` |
| `Intl.Segmenter` (grapheme) | user-perceived characters | 2 segments |
Tracking positions while you iterate
for...of does not give you an index. If you need an index you can pass to slice, keep a running code unit offset yourself and advance it by ch.length:
const text = 'hi 😀 there';
let offset = 0;
for (const ch of text) {
if (ch === '😀') {
console.log('emoji at code unit', offset); // emoji at code unit 3
console.log(text.slice(offset + ch.length)); // " there"
}
offset += ch.length;
}Counting with offset++ would drift by one after every astral character. An astral character is any character beyond U+FFFF. After the drift, later slices would cut text in the wrong place.
Where code points still fall short
A code point is still not always what a reader thinks of as one character. Unicode builds some visible characters, called grapheme clusters, out of several code points:
- An accented letter can be a base letter plus a combining mark:
'e\u0301'displays as é. - A family emoji is several person emoji joined by zero-width joiners (U+200D).
- A flag is two regional indicator symbols.
for...of splits all of these into their separate code points. To split by grapheme, use Intl.Segmenter, which is available in all modern browsers and in Node.js:
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}'; // 👨👩👧
const accent = 'e\u0301'; // é
const flag = '\u{1F1EF}\u{1F1F5}'; // 🇯🇵
console.log(family.length, [...family].length); // 8 5
console.log(accent.length, [...accent].length); // 2 2
console.log(flag.length, [...flag].length); // 4 2
const seg = new Intl.Segmenter('en', { granularity: 'grapheme' });
for (const { segment } of seg.segment(family + accent + flag)) {
console.log(segment, segment.length);
}
// 👨👩👧 8
// é 2
// 🇯🇵 4The object returned by seg.segment() is itself iterable. Each value it yields is an object, so destructuring { segment } in the loop head works the same way as the other destructuring patterns in this tutorial.
Edge case: lone surrogates
A string can hold a surrogate with no partner, for example after a bad slice or from malformed input. for...of does not throw on these. It yields each lone surrogate as a one-unit string, and codePointAt returns the surrogate's own value. You can test a string with isWellFormed() and repair it with toWellFormed(), which replaces lone surrogates with U+FFFD. Both methods arrived in ES2024.
const bad = 'x\uD83D';
for (const ch of bad) {
console.log(ch.length, ch.codePointAt(0).toString(16));
}
// 1 78
// 1 d83d
console.log(bad.isWellFormed()); // false
console.log(bad.toWellFormed() === 'x\uFFFD'); // trueCommon errors
- Checking a length limit with
str.lengthovercounts emoji, so a 10-emoji tweet registers as 20. - Truncating with
str.slice(0, n)can cut through a surrogate pair. Truncate with[...str].slice(0, n).join(''), or by grapheme withIntl.Segmenter. - Using
for...ofand assuming you get graphemes leaves flags and families split into pieces. - Writing an indexed loop with
i++while you callcodePointAt(i)visits the low surrogate on the next pass and returns a meaningless value. Either advance by the character's length or usefor...of.
Exercise
What does this code print, and why do the two numbers differ? const s = '😀😀x'; let a = 0; for (let i = 0; i < s.length; i++) a++; let b = 0; for (const c of s) b++; console.log(a, b);
Show answer
It prints 5 3. The indexed loop counts UTF-16 code units, and each 😀 takes two (a surrogate pair), so there are 2 + 2 + 1 = 5. for...of uses the string iterator, which yields one value per code point: 😀, 😀 and x, giving 3.
Exercise
Write a function truncate(str, n) that returns at most n user-visible characters, so that 'e\u0301' and a flag emoji each count as one character. Why is [...str].slice(0, n).join('') not enough?
Show answer
Use grapheme segmentation: function truncate(str, n) { const seg = new Intl.Segmenter('en', { granularity: 'grapheme' }); return Array.from(seg.segment(str), s => s.segment).slice(0, n).join(''); }. Spreading splits by code point, so a combining accent, a flag (two regional indicators) or a ZWJ family emoji counts as several characters and can be cut in the middle. For example, it can drop the accent from é or leave half a flag.
Exercise
You loop over a string with for...of and need the code unit index of each character so you can call str.slice. How do you compute it correctly?
Show answer
Keep a counter that starts at 0 and add ch.length after each iteration instead of 1. Characters outside the Basic Multilingual Plane have length 2, so adding 1 would leave the counter short by one for each such character and give wrong slice positions.