Home » JavaScript » JavaScript String Compare example

About Era Balliu

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.

JavaScript String Compare example

Comparing strings is a very common operation for most developers, 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

JavaScript Interview Coming Up?

Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!

In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!

 

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

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook