Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 394
Michael Schwartz Avatar asked Feb 18 '17 18:02

Michael Schwartz


1 Answers

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";
}
like image 132
Nina Scholz Avatar answered Oct 07 '22 08:10

Nina Scholz