1

Been looking for something where I could test if a variable has a certain word with switch statement:

JavaScript

var str = "We are VR Troopers";

switch (str) {
 case str.includes("are"):
   // do something;
   break;
  // no default
}

I have looked here and found nothing. Can you provide a link with your answers? That's a plus for my learning. Thanks.

I want to limit the use if too many if's.

Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

3

The simplest solution if you don't want to use if is to use the switch(true) construct.

I'd also suggest to avoid includes when you have a constant argument to check as its support is quite poor today (neither IE nor Edge support it) and to favor a regular expression instead (use a polyfill if your argument is variable).

See:

var str = "We are VR Troopers";

switch (true) {
 case /are/.test(str):
   // do something;
   break;
  // no default
}

You may improve it to test whether it's word, for example, or be case insensitive with expressions like /\bare\b/ or /are/i.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • is it a good practise to use regex inside switch case? Reference: http://stackoverflow.com/a/2896642/6237235 – Iceman Aug 06 '16 at 09:01
  • @Iceman it's not a bad practice per se but it turns out there's usually a better solution, which I can't infer from the too limited question (in this specific case the obvious solution is a `if`). – Denys Séguret Aug 06 '16 at 09:03
  • The answer works but using `if` maybe too much to type. – Sylar Aug 06 '16 at 09:06