Terminology (6)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Code point
- A number Unicode assigns to a character, written U+0041 for A. Emoji such as U+1F680 lie above U+FFFF.
- UTF-8
- An encoding that stores each Unicode scalar value in 1 to 4 bytes; lone surrogate code points are not valid UTF-8. ASCII takes 1 byte, most accented Latin letters 2, CJK characters 3 and emoji 4.
- UTF-16 code unit
- A 16-bit unit. JavaScript strings are sequences of them; a code point above U+FFFF takes two, called a surrogate pair.
- Continuation byte
- A UTF-8 byte of the form 10xxxxxx. It never starts a code point, so a cut must not land just before one.
- Grapheme cluster
- What a reader perceives as one character. It can be several code points, such as a letter with a combining accent or an emoji with a skin tone.
- Byte budget
- A storage or protocol limit counted in encoded bytes, such as a database column size or a push payload limit.
Why this matters
Form fields, database columns, push notifications and protocol headers all set limits on text, and they measure it differently. A form’s maxlength counts UTF-16 units, a storage contract may count encoded bytes or code points, and a reader counts what they see. Database types differ, so inspect the actual limit. A name that passes one check and fails another is a common production bug, and a careless cut can leave a broken character in the stored value.
This lesson assumes binary and hexadecimal and bit patterns from earlier lessons.
What a string length counts
Unicode code points identify elements of text. An encoding represents them with code units: UTF-8 uses bytes, while UTF-16 uses 16-bit units. A code point may require several units, so a string’s native length and its encoded byte size can answer different questions.
A visible character can also contain several code points, as with a combining mark or a flag. This lesson counts and truncates valid text at code point boundaries under a UTF-8 byte budget. Preserving an entire visible character requires grapheme segmentation, which is a separate boundary.
01Three lengths
Three lengths
The profile form allowed 12 characters and José Ñúñez has 10, yet the service rejected the name. Its legacy storage contract allows 12 bytes of UTF-8, and the name takes 14. A string has several lengths, and each limit counts one of them.
Predict the three lines this program prints for the name Zoë 🚀.
const name = "Zoë 🚀";
console.log(name.length); // the language's length
console.log([...name].length); // code points
console.log(new TextEncoder().encode(name).length); // UTF-8 bytes
| Text | Code points | UTF-16 units | UTF-8 bytes |
|---|---|---|---|
| A | 1 | 1 | 1 |
| é (U+00E9) | 1 | 1 | 2 |
| 李 (U+674E) | 1 | 1 | 3 |
| 🚀 (U+1F680) | 1 | 2 | 4 |
| 🇯🇵 (two regional indicators) | 2 | 4 | 8 |
02Budgets are bytes
Budgets are bytes
José Ñúñez has 10 code points and 10 UTF-16 units, so a form with maxlength 12 accepts it. In UTF-8, é, Ñ, ú and ñ take 2 bytes each, so the name is 14 bytes and the service’s 12-byte storage contract rejects it. Check the limit in the unit the storage uses: encode, then count bytes.
03Cut on a boundary
Cut on a boundary
🌸 is stored as the bytes F0 9F 8C B8. The first byte starts a code point and the other three have the form 10xxxxxx, continuation bytes. A cut placed just before a continuation byte splits the character. In TypeScript, cutting Anaïs 🌸 Dubois after 7 UTF-16 units keeps half of the surrogate pair, which encodes as the replacement character �. In Go and C++ a byte slice keeps the partial bytes, and Rust panics rather than build an invalid str.
To cut safely, walk forward by code point and stop before the next one would exceed the limit, or start at the limit and step back while the byte there is a continuation byte.
04Room for the ellipsis
Room for the ellipsis
A shortened name ends with “…”, which is one character and 3 bytes in UTF-8. Anaïs 🌸 Dubois is 18 bytes and the budget is 12.
Add the ellipsis only when the name is cut. A name of exactly 12 bytes fits and is stored whole; reserving the 3 bytes in every case would shorten it for no reason.
05What a reader sees
What a reader sees
06Store the display name
Store the display name
The profile service first needs to know what its count represents: code points are different from native string length. Saving the same name then requires the storage contract’s UTF-8 byte count. When a name is too large, keep the longest code point prefix that leaves room for the visible truncation marker; a name that already fits needs neither a cut nor a marker.
A profile service
Count code points, check the bytes, then shorten on a code point boundary.
In the frontend A byte counter in Next.js and Svelte Optional
When the server stores 64 bytes, maxlength="64" still accepts up to 192. Count the encoded bytes as the user types and mark the field invalid past the budget. The server checks again, because a client check can be bypassed.
"use client";
import { useState } from "react";
const BUDGET = 64; // bytes the server stores
const encoder = new TextEncoder();
export function DisplayNameField() {
const [name, setName] = useState("");
const bytes = encoder.encode(name).length; // maxlength would count UTF-16 units
return (
<label>
Display name
<input
value={name}
onChange={(event) => setName(event.target.value)}
aria-invalid={bytes > BUDGET}
/>
<small>
{bytes} / {BUDGET} bytes
</small>
</label>
);
}
See MDN: TextEncoder and MDN: maxlength.
Check this idea later
Sources
- The Unicode Standard, chapter 3: UTF-8 and UTF-16 encoding forms
- RFC 3629: UTF-8
- ECMAScript: the String type
- Go blog: Strings, bytes, runes and characters
- Rust: str
- Unicode Standard Annex #29: text segmentation
Counts above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The profile service is a worked model.
Sign in to keep your read marks on every device. Sign in
Was this helpful?