12

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

2
  • compare === "page2" ? Seems like an odd question for you to have. Commented Feb 18, 2017 at 18:47
  • compare === "page1" || compare === "page2" Commented Feb 18, 2017 at 18:47

4 Answers 4

19

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Be careful with this approach. In my case, compare can also be page1_other. Which, with this approach, would get wrongly validated.
@jbarradas I check your case compare="page1_other" and includes give false for this case - which is correct (according to OP question)
2

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.