- To compare strings based on their values and characters case, use the Strict Equality Operator (===).
- To compare strings based on their length, utilize the “length” property in combination with “Comparison operators”.
- To compare strings based on alphabetical order, use the “localeCompare()” method.
Now, we will discuss each of the mentioned procedures in the next sections.
The Strict Equality Operator “===” operator is primarily utilized to compare the value of two string operands. The term “strict” distinguishes it from the equality operator “==“, as it strictly compares the values of strings without converting them into a common type.
Here, the Strict Equality operator “===” will compare “x” and “y” values and return a “Boolean” value.
First of all, we will create two strings named “string1” and “string2” having the following values:
In the next step, we will compare “string1” and “string2” using the Strict Equality operator “===”:
As values of both strings are not equal, so the Strict Equality operator will return “false“:
In the next statement, we will compare the “string1” value with the “linux” string:
Both values are equal according to their associated data type and characters case, so the strict equality operator will mark them as equal and return a “true” boolean value:
If you want to perform “case-insensitive” comparison, convert both strings into lowercase with the help of the “toLowerCase()” method and then compare them:
In this case, when the value of the “string3” is converted to lowercase, it becomes “linux,” which is equal to the “string1” value. That’s why the execution of the above-given Equality operator will return “true”:
For instance, the below-given condition will check if the length of “string1” is greater than “string2” length or not:
The string1 “linux” comprises five characters, and string2 “hint” contains four characters. This states that the length of “string1” is greater than the length of “string2“, so after comparing length, the “Greater than” operator will return “true”:
Now, let’s check out the method of comparing strings based on their alphabetical order.
The “localeCompare()” method accepts an argument “string2,” which will be compared with “string1”.
To demonstrate the usage of the localeCompare() method, firstly, we will define three strings, “string1”, “string2”, and “string3” with the following values:
Then, we will pass “string2” as an argument to the “localeCompare()” method to compare it with “string1”:
The “localeCompare()” method will return “1” because “string1” is alphabetically greater than “string2”:
In contrast, if “string1” comes before “string2” or is smaller than the invoked “localeCompare()” method will return “-1”:
Lastly, the “localeCompare()” method will return the value “0” when both strings are equal: