How to Compare Strings Correctly in JavaScript

November 5, 2017

A common mistake that most programmers make is trying to compare their strings with == in Java. There is a good reason why this never works, as you will find out, plus there are three prominent ways to compare strings and get true results. Three most accurate ways to compare strings correctly in JavaScript. The == operator has its limitations here because Java is not designed to support it.

Why the == operator doesn’t work in JavaScript

The explanation is simple; Java wasn’t built to work with == as an option to compare strings. The developers of Java had the vision to keep things simple in programming thus did away with the == operator and in its place introduced three unique ways to test strings. Below are the 3 ways to compare your strings and not get any reference errors.

Using the ‘equals’ method

This is a frequently used, and preferred, option among experienced programmers. The equals method compares two strings and determines whether they contain similar characters. If all characters in the two strings are identical, then the operator gives a true or equal answer.

Here is a quick example of how two strings that don’t contain the same characters give a false result false

Now below is a second example on how two strings are compared to give an equal result

Thus the lines in the second example will print.

Comparing strings with the EqualsIgnoreCase method

his method is used in special cases where the programmer wants to compare strings that are case sensitive. The operator will ignore whether the strings have uppercase or lowercase characters and proceed to compare them as shown in the diagram below.

Comparing Strings with ‘CompareTo’ Operator

This is the third option for comparing strings. Though it is not a frequently used method, it gives more accurate results than using == operator. The CompareTo operator puts two strings side by side, and if they all have identical characters it gives a result of zero. Below is an example of this’

These are the three most accurate ways to compare strings in JavaScript. The == operator has its limitations here because Java is not designed to support it.



Article by Sifat Author
Published on: November 5, 2017
Last updated on:

Leave a Reply

Your email address will not be published. Required Fields are Marked *