EXAMTOPICS / TECHNOLOGY INSIGHTS

JavaScript String Equality: Exact, Unicode and Locale-Aware

Start by defining what “equal” means

Two strings can be identical as program data while two other strings appear identical to a person but contain different Unicode sequences. Efficient comparison begins by identifying the actual requirement: exact identity, a normalized key, a case-insensitive user-facing match, or a language-aware comparison. JavaScript offers different operations for those situations; none should be applied to every input without considering the consequences.

For program identifiers, filenames, signed values and protocol fields, exact comparison is often essential. For a contact search or language-sensitive name list, a less restrictive comparison may be appropriate. Mixing those contexts can cause subtle security and correctness errors. The fastest operation that answers the wrong question is not an optimization.

Use strict equality for exact strings

The strict equality operator (===) checks that both operands have the same type and value. For primitive strings, their characters must match in the same order. It does not trim whitespace, ignore capitalization, change Unicode normalization or convert numbers into strings.

console.log("hello" === "hello"); // true
console.log("Hello" === "hello"); // false
console.log("5" === 5);           // false
console.log("dog " === "dog");     // false

This should be the default equality operator in ordinary JavaScript. The loosely equal operator (==) may coerce values of different types; that behavior creates ambiguity when user input has not been validated. An application expecting strings should check that it received strings rather than relying on implicit conversion of undefined, null or a numeric identifier.

Validate types before text processing

A function that calls trim or normalize on an unexpected null value will throw. Make the contract explicit: either reject nonstrings, convert selected types intentionally, or handle a missing value as a distinct business state. Converting every value with String(value) can turn undefined into the literal text “undefined,” which is rarely appropriate when checking required input.

function exactMatch(a, b) {
    if (typeof a !== "string" || typeof b !== "string") {
        throw new TypeError("Two strings required");
    }
    return a === b;
}

console.log(exactMatch("A-42", "A-42")); // true

If an input originates in a form, define whether an empty string is legitimate. Authentication credentials, customer reference codes and human-readable display names may need different validation policies. Do not reuse a text-search helper for values that are intended to remain byte-exact.

Whitespace and case changes require intent

Calling trim removes leading and trailing whitespace in the set recognized by JavaScript. That may be sensible for a casual search box but inappropriate for a password or an exact document identifier. A code beginning with a space may be erroneous user input that should be rejected rather than silently corrected. Similarly, lowercasing is useful only when the domain considers case differences unimportant.

const typed = "  Welcome  ";
const expected = "welcome";
const sameForSearch =
    typed.trim().toLowerCase() === expected;

console.log(sameForSearch); // true

Case folding is not the same operation as full language-aware equality. Some languages have distinct rules for dotted and dotless letters and other characters. JavaScript’s toLocaleLowerCase can use a specified locale, but it is not a universal normalization function that makes all words comparable. Use an explicit language policy for products serving multiple languages.

Unicode normalization and visually identical strings

Unicode can represent an accented letter as a single precomposed code point or as an ordinary letter followed by a combining mark. Those sequences may display identically while strict equality returns false. The String.prototype.normalize reference describes canonical normalization with NFC and NFD, and compatibility normalization with NFKC and NFKD.

const composed = "café";
const decomposed = "cafe\u0301";

console.log(composed === decomposed); // false
console.log(
    composed.normalize("NFC") ===
    decomposed.normalize("NFC")
); // true

For a natural-language identifier where canonical equivalence is intended, applying the same normalization form to both operands can be helpful. However, compatibility normalization can deliberately erase distinctions: a ligature or compatibility symbol may be transformed into a different sequence. That might improve search recall while being unacceptable for a legal identifier, a cryptographic signature or an account name with established uniqueness rules.

Normalize consistently when records are entered or indexed, not only at comparison time. If older data uses mixed conventions, document how collisions will be detected and resolved. Never silently overwrite two distinct existing records merely because a new comparison policy treats their labels as equivalent.

Use Intl.Collator for language-aware equivalence

A person comparing names, search terms or a list in a particular language may care about differences in accents and case differently from a protocol parser. The localeCompare documentation explains that comparisons can use locale-sensitive collators with options such as sensitivity. A comparison returns a negative, zero or positive number; do not rely on an exact nonzero result of -1 or 1.

const collator = new Intl.Collator("en", {
    sensitivity: "base"
});

console.log(
    collator.compare("résumé", "resume") === 0
); // true in an English collation

Constructing a single Intl.Collator can be preferable when comparing many values, for example while sorting a large list. Reuse its compare function rather than constructing equivalent locale-comparison settings for every pair. Remember that equality under one locale and sensitivity is not the same as exact Unicode identity; define what equivalences are acceptable to the product.

Equality and ordering are different questions

Strict equality asks whether two string values are the same. Lexicographic operators such as less-than answer an ordering question, and locale-aware comparison answers a potentially different ordering question. Sorting names for display may require a collator; checking an API constant should not. If comparison rules change, a previously sorted list or deduplication strategy may also change.

For large collections, a hash set or Map can make repeated exact lookups clearer and often more efficient than scanning the entire array. But using a Set with strings uses its defined key equality, not localeCompare. To deduplicate according to a custom normalization policy, compute a canonical key deliberately and decide how to retain the original spelling and how to handle collisions.

const identifiers = new Set(["A-1", "A-2"]);
console.log(identifiers.has("A-1")); // true
console.log(identifiers.has("a-1")); // false

Where a UI supports accent-insensitive search, a separate search index may be appropriate. Keep display labels intact, store the search key separately and test how the index handles punctuation, ligatures and languages that do not use Latin scripts.

Do not use convenience comparisons for secrets

Comparing authentication tokens, message authentication codes or cryptographic digests creates a different security problem. String === is not documented as a constant-time primitive and should not be claimed to protect against timing analysis. Use a maintained cryptographic comparison routine available in the platform, with appropriately validated byte lengths and error handling. A locale-aware or case-folded comparison would be particularly wrong for secret values whose exact bytes matter.

A password should normally be verified through an approved password-hashing scheme with salt and suitable work factors rather than compared as raw plaintext. Security decisions also require rate limiting, logging that excludes secrets and authorization controls. String comparison is one part of a much larger security design.

Test the cases that matter to your users

Build tests around the chosen comparison policy: exact matches, wrong types, leading or trailing spaces, case differences, composed and decomposed accents, language-specific capitalization, invisible characters and empty values. If the application uses a collator, test the product’s supported locales and selected sensitivity. Do not assume a result from one browser locale holds under every setting.

For example, a user directory might match normalized names for searching yet require exact immutable user IDs for access control. Test each independently. A failing comparison often means the policy was not specified rather than the JavaScript engine performing a mysterious operation. Add regression tests whenever a normalization or collation rule changes, especially if duplicates or search behavior affect existing records.

Choose the simplest comparison with the correct semantics

Use === for ordinary exact strings. Normalize with NFC only when canonical equivalence is part of the documented data contract. Trim and transform case only for fields where that loss of distinctions is acceptable. Use Intl.Collator for locale-sensitive matching or ordering, and use cryptographic APIs for secret comparisons. The right optimization is a correct, well-tested policy with no unnecessary conversions—not a universal trick that claims to make every pair of strings equal efficiently.