Michael Schwartz
Michael Schwartz

Reputation: 8415

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 statement.

var compare = "page3";

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

Upvotes: 12

Views: 145417

Answers (4)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92367

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";
}

Upvotes: 3

Nagibaba
Nagibaba

Reputation: 5358

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)){...}

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65806

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;
}

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

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";
}

Upvotes: 19

Related Questions