What You'll Learn
You'll learn how to use normalize() to ensure that visually identical strings are represented the same way internally, fixing hidden Unicode inconsistencies.
The Unicode Problem
In Unicode, some characters can be represented in multiple ways. For example, the letter "é" can be stored as:
- A single character (é)
- Two separate characters: "e" + a combining accent (´)
Both look identical when displayed, but JavaScript sees them as different strings! This creates bizarre bugs where "café" doesn't equal "café".
Think of it like spelling "café" versus "cafe´" — they look the same on paper, but the letters are arranged differently behind the scenes.
Using normalize()
The normalize() method converts strings to a standard Unicode form so equivalent characters match:
let single = "café"; // é as one character
let combined = "café"; // e + combining accent
console.log(single === combined); // false — different representations!
let norm1 = single.normalize();
let norm2 = combined.normalize();
console.log(norm1 === norm2); // true — now they match!
Normalization Forms
normalize() accepts an optional form: "NFC" (default, composed), "NFD" (decomposed), "NFKC", or "NFKD". For most cases, the default "NFC" works perfectly:
let text = "Zürich";
let normalized = text.normalize("NFC"); // Ensures consistent form
When to Use It
Use normalize() when:
- Comparing user input that might contain accented characters
- Storing text in databases where consistency matters
- Processing international text from different sources
Key Takeaway: Use normalize() to convert strings into a consistent Unicode form, ensuring that visually identical text compares as equal.