@FahadM to JavaScriptEnglish • 4 days ago

How do you perform a case-insensitive string comparison in JavaScript?

message-square
0
1
How do you perform a case-insensitive string comparison in JavaScript?
@FahadM to JavaScriptEnglish • 4 days ago

To perform a case-insensitive string comparison in JavaScript without mutating the original strings, normalize both values to the same case—most commonly via String.prototype.toLowerCase() or String.prototype.toUpperCase()—and compare with ===, or use String.prototype.localeCompare(other, undefined, { sensitivity: "base" }) === 0 when you want locale-aware collation (such as accented characters or Turkish "i"/"İ" rules). Avoid deprecated localeCompare flags without options when base-level equality is intended, and always guard against non-string inputs at runtime.


1. Standard Case-Insensitive Equality with toLowerCase() and ===

Convert both strings with .toLowerCase() and compare with strict equality (===) for straightforward, fast, non-mutating comparisons:

// Non-mutating case-insensitive equality check using toLowerCase()
function equalsIgnoreCase(left, right) {
  if (typeof left !== "string" || typeof right !== "string") {
    throw new TypeError("Expected both left and right arguments to be strings.");
  }

  return left.toLowerCase() === right.toLowerCase();
}

// Example usage:
const roleA = "Admin";
const roleB = "ADMIN";
console.log(equalsIgnoreCase(roleA, roleB)); // true
console.log(roleA); // "Admin" (original string unchanged)
  • Immutable strings: .toLowerCase() returns a new string and never alters the original inputs.
  • Strict equality (===): Using === after normalizing avoids loose coercion surprises.

2. Locale-Aware Comparison with Intl.Collator / localeCompare

For human-facing text, accented letters (like "é" vs. "É"), or locale-specific alphabets, use Intl.Collator or localeCompare with { sensitivity: "base" } so accents and case differences are treated appropriately for the target locale:

// Locale-aware case-insensitive comparison treating base characters as equal
function equalsIgnoreCaseLocale(left, right, locales = undefined) {
  if (typeof left !== "string" || typeof right !== "string") {
    throw new TypeError("Expected both left and right arguments to be strings.");
  }

  const collator = new Intl.Collator(locales, { sensitivity: "base" });
  return collator.compare(left, right) === 0;
}

// Example usage:
console.log(equalsIgnoreCaseLocale("café", "CAFÉ", "en")); // true
console.log(equalsIgnoreCaseLocale("İstanbul", "istanbul", "tr")); // true
  • Reuse Intl.Collator in loops: Constructing new Intl.Collator(...) once outside a loop or sort comparator avoids repeated locale initialization overhead.
  • Turkish "I" / "i" nuance: In Turkish ("tr"), uppercase "I" maps to dotted/dotless rules differently than in English ("en"), making locale-aware comparison valuable when language context matters.

3. Trimming, Null-Safety, and Searching Substrings Case-Insensitively

When comparing user input, normalizing whitespace with .trim() before casing prevents leading or trailing spaces from causing false mismatches, and using .toLowerCase().includes(...) handles case-insensitive substring checks:

// Guarded helper for case-insensitive substring search with optional trimming
function includesIgnoreCase(haystack, needle, { trim = true } = {}) {
  if (typeof haystack !== "string" || typeof needle !== "string") {
    throw new TypeError("Expected both haystack and needle to be strings.");
  }

  const normalizedHaystack = trim
    ? haystack.trim().toLowerCase()
    : haystack.toLowerCase();
  const normalizedNeedle = trim
    ? needle.trim().toLowerCase()
    : needle.toLowerCase();

  return normalizedHaystack.includes(normalizedNeedle);
}

// Example usage:
console.log(includesIgnoreCase("  Node.js Streams Guide ", "streams")); // true
console.log(includesIgnoreCase("Hello World", "xyz")); // false
  • Guard nullable/external values: If inputs may be null or undefined from APIs or forms, validate or convert safely before calling .toLowerCase() so you do not throw a TypeError.
  • Prefer .toLowerCase().includes() over dynamic new RegExp(needle, "i"): Avoid building regexes from untrusted strings unless you escape regex metacharacters first.

TL;DR: Use a.toLowerCase() === b.toLowerCase() for fast, non-mutating case-insensitive equality, or new Intl.Collator(locales, { sensitivity: "base" }).compare(a, b) === 0 when locale-sensitive character rules apply.