Why can two identical-looking strings compare as different Unicode text?
Quick answer
Two strings can look identical yet contain different Unicode code-point sequences. For example, ñ can be one code point or an n followed by a combining tilde; direct JavaScript string equality treats those sequences as different. Normalize both strings to a common form, such as NFC, before comparing when canonical equivalence is what you mean. Do not assume every system normalizes automatically, and use compatibility forms only when their broader changes fit your needs. [S1]
The question, the details, the next step.
A practical checklist
Save a short example of each string that compares unexpectedly.
Confirm whether the comparison is direct equality or applies normalization.
If canonical equivalence is intended, normalize both strings to the same form, such as NFC, before comparing.
Check that a compatibility form is appropriate before using NFKC or NFKD, since it can change appearance.
Test representative cases in the actual system that performs the comparison; do not assume it normalizes text automatically.
A few more useful answers
Does NFC make every pair of visually similar strings equal?
No. NFC and NFD address canonically equivalent sequences; they are not a general rule for treating all visually similar text as equal. [S1]
Will JavaScript normalize strings automatically when I use `===`?
No. Direct equality treats the two ñ sequences as different. Call normalize() on both strings when that is the comparison you intend. [S1]
Should I use NFKC for every text comparison?
No. NFKC and NFKD fold some compatibility distinctions and may change appearance, so whether they fit depends on which distinctions your task should preserve. [S1]
Sources
References used for this guide.
- [S1] String.prototype.normalize() — JavaScript | MDN developer.mozilla.org · Checked
