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.

0

1 Answer 1

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.

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

3 Comments

is it a good practise to use regex inside switch case? Reference: stackoverflow.com/a/2896642/6237235
@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).
The answer works but using if maybe too much to type.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.