Skip to content Skip to sidebar Skip to footer

How To Compare Two Strings In Javascript If Condition

I'm having trouble recalling how to compare these two strings in an if statement. What I'm string to do is check if my variable compare equals page1 or page2 if not, go to the else

Solution 1:

You could check every option.

if (compare === "page1" || compare === "page2") {

Or you could use an array and check with an existential quantifier like Array#some against, like

if (["page1", "page2"].some(a => a === compare)) {

var compare = "page3";

if (compare === "page1" || compare === "page2") {
    document.body.innerHTML = "github url";
} else {
    document.body.innerHTML = "non-github url";
}

Solution 2:

Try

if( ["page1", "page2"].includes(compare) ){...}

var compare = "page3";

if( ["page1", "page2"].includes(compare) ) {
  document.body.innerHTML = "github url";
} else {
  document.body.innerHTML = "non-github url";
}

Solution 3:

Anytime you have multiple things to check in an if condition, you must write each condition separate from the other. So, the test must be written as:

// If compare equals "page1" OR compare equals "page2"
if (compare === "page1" || compare === "page2") {

When you have a single variable that may contain many different values, using a switch statement can be more logical and more efficient since it only has to look up the value of the variable one time.

Also, remember that strings are literals and "page1" does not equal "Page1". To make a comparison that is case-insensitive, you can force all the values to lower (or upper) case first and then check them against each other (as shown here):

switch (compare.toLowerCase()) {
    case "page1" :
        // Do work here
        break;
    case "page2" :
        // Do work here
        break;
    case "page3" :
        // Do work here
        break;
    default :
        // Do work here
        break;
}

Solution 4:

a.localeCompare(b) is another cool way of comparing larger strings

function areEqual(a, b){


  if (a.length !== b.length) {
         return false;
  }

  return a.localeCompare(b) === 0;
}


if(areEqual(a,b)){...}

Post a Comment for "How To Compare Two Strings In Javascript If Condition"