Is it possible to use .contains() in a switch statement?

“Yes”, but it won’t do what you expect.

The expression used for the switch is evaluated once – in this case contains evaluates to true/false as the result (e.g. switch(true) or switch(false))
, not a string that can be matched in a case.

As such, the above approach won’t work. Unless this pattern is much larger/extensible, just use simple if/else-if statements.

var loc = ..
if (loc.contains("google")) {
  ..
} else if (loc.contains("yahoo")) {
  ..
} else {
  ..
}

However, consider if there was a classify function that returned “google” or “yahoo”, etc, perhaps using conditionals as above. Then it could be used as so, but is likely overkill in this case.

switch (classify(loc)) {
   case "google": ..
   case "yahoo": ..
   ..
}

While the above discusses such in JavaScript, Ruby and Scala (and likely others) provide mechanisms to handle some more “advanced switch” usage.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)