JavaScript: Ways to Compare 2 Strings Ignoring Case

Updated: February 28, 2023 By: Wolf Post a comment

This succinct, example-based article walks you through 3 different ways to compare 2 strings ignoring cases (regardless of lowercase and uppercase, for example, A and a are considered equal) in JavaScript.

Using toLowerCase() or toUpperCase() and the === operator

The technique is intuitive and easy to understand. First, we convert both strings to lowercase or uppercase using the toLowerCase() or toUpperCase(). Next, we use the === operator to compare them.

Example:

const str1 = 'Sling Academy';
const str2 = 'sling academy';

if (str1.toLowerCase() === str2.toLowerCase()) {
  console.log('Strings are equal ignoring case.');
} else {
  console.log('Strings are not equal.');
}

Output:

Strings are equal ignoring case.

Using localeCompare()

Another solution is to use the localeCompare() method with the ignoreCase parameter set to true. This method returns 0 if both strings are equal, regardless of their case.

Example:

const str1 = 'WELCOME TO SLING ACADEMY';
const str2 = 'Welcome to sling academy';

const result = str1.localeCompare(str2, undefined, { sensitivity: 'base' });

if (result === 0) {
  console.log('Strings are equal ignoring case.');
} else {
  console.log('Strings are not equal.');
}

Output:

Strings are equal ignoring case.

Using regular expressions

If a regular expression is created using the RegExp() constructor with the i flag, which means it is case-insensitive.

Example:

const str1 = 'The fire is getting bigger and bigger.';
const str2 = 'THE FIRE IS GETTING BIGGER AND BIGGER.';

const regex = new RegExp(str1, 'i');

if (regex.test(str2)) {
  console.log('Strings are equal ignoring case.');
} else {
  console.log('Strings are not equal.');
}

Output:

Strings are equal ignoring case.

The test() method is used to check if the second string matches the regular expression created from the first string, ignoring case.