How to Compare Strings in JavaScript

If you enjoy making web pages and have used JavaScript in the past, you may want to learn this technique of comparing two strings in JavaScript.

Originally, JavaScript was patterned on Java. However, JavaScript's means of comparing strings is quite different.

To find out how to compare strings in JavaScript, read on.

Things You'll Need

  • Basic knowledge of the JavaScript language
Show More

Instructions

    • 1

      First to compare strings in JavaScript, you need to be sure that the strings that will be compared aren't null. "Null" just means that one of the strings hasn't been assigned a value yet so the value is "null".

    • 2

      If you have 2 strings, you can check to see if they are null:

      if (string1 == 'null') will return true if string1 is null.

      You could also do:

      if (string1 != 'null' && string2 != 'null') {
      //compare the strings here
      }

    • 3

      Once you know that the strings aren't null, you simply type

      if (string1 == string2) {}

      This will tell you if the strings are the same.

      Also:

      if (string1 == 'happy') is valid.

    • 4

      That's all it takes to compare strings in JavaScript. Good luck!

Tips & Warnings

  • Once you are sure that both strings are null, you can compare the first string to the second string.

Related Searches:

Resources

Comments

You May Also Like

Related Ads

Featured