JavaScript

JavaScript String Compare example

A very common operation for most developers is String Compare, be the language they use JavaScript, C/C++, Java, whatever. To be honest, the programming language doesn’t even matter. At some point you will have to compare those strings. In this example we will learn how to do that using JavaScript.

We will use:

  • JavaScript

Simple Comparison

We will start by having you give a look at the following example:

var s = 'string1';

if(s == 'string1') {
    alert(true);
} else {
    alert(false);
}

You will notice that the code puts an alert that says true on the screen. Pretty logical, as the strings are obviously equal.But…

Comparing strings with numbers?!

Have a look at the following code snippet:

var s = '16';

if(s == 16) {
    alert(true);
} else {
    alert(false);
}

It shows true. Confused much? Are you asking yourself why did it turn out true when a string can’t possibly be equal to a number? I will tell you why after you look at this improved version of the last code:

var s = '16';

if(s === 16) {
    alert(true);
} else {
    alert(false);
}

Did you notice the difference? It’s in the operator: We were using == and now we’re using ===. While the first one only checks if the variables are equal, the second one also considers the variable types, which should be the same too. That’s why the improved example will show you the result false. If it still seems strange why would JavaScript consider 123 as equal to ‘123’ then let me tell you JavaScript comparison operator use .toString() operators for types that are not strings.

Case insensitive string comparison

Sometimes you want to compare strings that only differ by one being sentence case and the other lowercase or uppercase. But if you are only interested in the content and not the formatting, the comparison way we showed you in the previous paragraphs is not very convenient.

One way would be to convert both strings to uppercase and then compare, which would make the code go like this:

var str1 = "Sentence Case";
var str2 = "sentence case";
var res1 = str1.toUpperCase();
var res2 = str2.toUpperCase();

if(res1 == res2) {
    alert(true);
} else {
    alert(false);

Remember that casing is a locale specific operation. Depending on the scenario you may want to take that in to account. For example, if you are comparing names of two people you may want to consider locale but if you are comparing machine generated values such as UUID then you might not.

It is preferred to normalize your strings to uppercase, though you can even normalize them to lowercase. That’s because a small group of characters, when turned to lowercase make a round trip, which means they convert to a different locale, showing character data differently (here you have an example of the problem).

Also, please note that in some languages even normalizing characters to uppercase can result in errors, as is the example of Turkish language.

In these cases we might further improve the previous code by using the following function:

function compareStrings (string1, string2, ignoreCase, useLocale) {
    if (ignoreCase) {
        if (useLocale) {
            string1 = string1.toLocaleLowerCase();
            string2 = string2.toLocaleLowerCase();
        }
        else {
            string1 = string1.toLowerCase();
            string2 = string2.toLowerCase();
        }
    }

    return string1 === string2;
}

That is how you compare strings in JavaScript, taking into account the problems you may encounter in doing so.

Download the source code for JavaScript String Compare Example

This was an example of string comparison, using JavaScript.

Download
You can download the source code for this example here: StringCompareJavascript

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button