INSIGHTS
Software Development

How to Compare Strings in JavaScript: Methods, Examples, and Best Practices

In this article
  1. Use strict equality for exact matches
  2. Normalize before a deliberately case-insensitive check
  3. Use a locale-aware collator for user-visible text
  4. Understand Unicode normalization
  5. Compare numbers as numbers, not as text
  6. Test the comparison contract

Comparing JavaScript strings is straightforward only after you decide what “equal” means. A literal token match, a case-insensitive search, a human-language sort and a Unicode-normalized comparison are different operations. Choosing the wrong one can reject legitimate names, misorder results or accept text that should remain distinct. These examples show how to select the rule deliberately.

Use strict equality for exact matches

const storedCode = "AB-104";
console.log(storedCode === "AB-104"); // true
console.log(storedCode === "ab-104"); // false
console.log("15" === 15);             // false

=== compares strings without coercion. It is appropriate for case-sensitive program identifiers, fixed status tokens or protocol fields whose exact bytes have contractual meaning. Do not use the looser == to “help” with mismatched input types: converting numbers and other values during comparison obscures validation errors.

Normalize before a deliberately case-insensitive check

const left = "  Warning ";
const right = "warning";
console.log(left.trim().toLowerCase() === right.toLowerCase());
// true

Trimming and lowercasing can be useful when comparing simple English labels. These changes are destructive to information: whitespace, accents and case may be meaningful in usernames, identifiers or passwords. For security-sensitive tokens use the exact server-defined comparison, not a convenience normalization. JavaScript case conversion also has language-specific edge cases, so this recipe is not a universal human-name matcher.

Use a locale-aware collator for user-visible text

const en = new Intl.Collator("en", {
  usage: "search",
  sensitivity: "base"
});
console.log(en.compare("Résumé", "resume") === 0); // true

const names = ["Zoe", "Émile", "Ana"];
const sortEn = new Intl.Collator("en", { sensitivity: "base" });
console.log([...names].sort(sortEn.compare));

A collator follows language-aware rules when comparing user-facing text. The return value of compare() may be negative, zero or positive: never assume it returns exactly -1 or 1. Select sensitivity and locale according to the product’s search or sorting requirements. A collator that ignores accents is inappropriate when different accented names must remain distinguishable.

Understand Unicode normalization

const composed = "é";
const decomposed = "e\u0301";
console.log(composed === decomposed); // false
console.log(composed.normalize("NFC") ===
            decomposed.normalize("NFC")); // true

Two strings can render identically while containing different Unicode code point sequences. normalize("NFC") produces a canonical composition suitable for many consistent comparisons. It is not a security policy, transliteration or guarantee that visually confusable characters have become the same. For authentication, identity claims and reserved identifiers, follow the backend’s explicitly defined normalization and uniqueness rules.

Compare numbers as numbers, not as text

console.log("20" < "3"); // true: character order
console.log(Number("20") < Number("3")); // false

Lexicographic ordering follows character values, so the text "20" comes before "3". Parse and validate numeric values when you need numeric order. Guard against NaN, empty strings, very large values and formats the parser cannot interpret. For natural sorting of labels that contain digits, consider Intl.Collator with { numeric: true } after checking the desired locale.

Test the comparison contract

  • Exact-match test: compare equal strings, mixed case and different types.
  • User-search test: check whitespace, accent sensitivity and locale-specific letters.
  • Unicode test: compare composed and decomposed characters after intentional normalization.
  • Sorting test: verify names, numbers embedded in strings, and stable fallback ordering.

A robust comparison function starts with the user’s intent, not an operator chosen out of habit. MDN’s Intl.Collator reference documents language-sensitive search and sort behavior. Use === when a literal is the contract and a collator when human-language equivalence is the contract.

Filed under Software Development