Unicode and UTF-8 explained: why text handling goes wrong in code
Text seems simple until an emoji breaks your string length, a name displays as garbled symbols, or sorting puts accented letters in odd places. Most of these problems come from misunderstanding Unicode.
Key concepts
- Unicode assigns a number (a code point) to characters from virtually every writing system, plus symbols and emoji.
- Encodings turn code points into bytes. UTF-8 is the dominant encoding on the web: ASCII characters take one byte, others take two to four.
- UTF-16 is used internally by some languages and platforms, including JavaScript strings and Windows APIs.
Why "length" is tricky
A single visible character (a grapheme cluster) can be several code points: a letter plus a combining accent, a flag made of two regional indicators, or an emoji with skin-tone modifiers joined together. Depending on the language, length might count bytes, UTF-16 units or code points, none of which equal "characters a human sees."
Common bugs
- Mojibake: garbled text from decoding bytes with the wrong encoding.
- Truncating strings mid-character, producing invalid sequences.
- Comparing strings that look identical but use different normalization forms (precomposed vs combining accents).
- Case conversion assumptions that don't hold in every language.
- Reversing strings naively, which can break emoji and combined characters.
Good habits
- Use UTF-8 everywhere: files, databases, HTTP headers.
- Decode bytes at the edges of your program and work with text internally.
- Normalize before comparing user input.
- Use libraries that understand grapheme clusters for user-facing lengths and truncation.
What's the strangest text-encoding bug you've debugged?
Comments · 2
So length("😀") can be different in different languages because it counts bytes, code points or characters. That finally explains why my loop gave a weird number.
Rule: store and exchange text as UTF-8, and decode at the edges. Never assume one character equals one byte.