How to perform String comparison in JavaScript

Overview

The String is zero or more characters embraced with a single or double quote in JavaScript. Anything can be put inside a string to be stored for future use.

A developer may need to compare two strings while writing codes to check various things that need to be done.

How do we get this done when JavaScript itself is case-sensitive by default?

Comparing strings

We can make a case-insensitive String comparison by using the following three ways in JavaScript:

  1. The abstract equality == or strict equality === operator.
  2. The .localeCompare() method.
  3. Regular expression.

Note: We’ll discuss only equality operators in this shot.

Using the equality operators

The equality operators compare two strings if they are equal.

let stringA = 'Bird';
let stringB = 'bird';
if(stringA == stringB){
console.log("The strings have the same characters.");
} else {
console.log("The strings ain't the same.");
}

Explanation

Here’s the explanation of the above code:

  • Lines 1 and 2: We create two variables, stringA and StringB, and assign some strings to them. StringA starts with a capital letter while stringB starts with a small letter, but both have the same character.

  • Line 4: We use an if/else statement to compare the two strings. It returns a sentence to the console if the string is the same and another sentence if the string is not the same.

We check the console and The strings ain't the same. is printed to the console. Because JavaScript is case-sensitive, it doesn’t recognize both strings with the same characters.

How do we solve this?

First, we need to compare both strings in lowercase or uppercase using .toLowerCase and .toUpperCase before comparison.

This will give a perfect comparison.

let stringA = 'This is a Bird';
let stringB = 'this is A birD';
if(stringA.toLocaleUpperCase = stringB.toUpperCase){
console.log('The strings are perfectly the same.');
} else {
console.log('The strings ain\'t the same');
}
// or betterstill
/*
if(stringA.toLocaleLowerCase = stringB.toLowerCase){
console.log('This strings are perfectly the same.');
} else {
console.log('The strings ain\'t the same');
} */

Explanation

  • Lines 1 and 2: We create two variables and assign them with strings of identical letters but in different cases.

We compare these two strings using the equality operator.

  • Line 3: We create an if/else statement. In this condition (the brackets after if), the two strings are converted to uppercase. So it has to be identical before comparison (why? because JavaScript is case sensitive). Then the code blocks to execute are created.

When we check the console, it prints The strings are perfectly the same because the condition is met.

The code above clearly solves the problem as it compares the two strings perfectly.

In this shot, you learned how to compare case insensitive strings using the equality operator.

Free Resources