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?
We can make a case-insensitive String comparison by using the following three ways in JavaScript:
==
or strict equality ===
operator..localeCompare()
method.Note: We’ll discuss only equality operators in this shot.
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.");}
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');} */
We compare these two strings using the equality operator.
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.