Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch combining cases string regex and number

Is there a way to create multiple cases in a single Javascript switch statement?

In my code I receive the value of a field via jQuery.

Is it possible that one case checks for string regex and another for number of the same variable?

I am thinking along the lines of:

var field = $(this).val();
var msg;
switch (field) 
{
    case field.test('Yes'):

     msg = "FOO\n";
     break;

    case 10: 
     msg = "BAR\n";
     break;
}

Although I saw here: Switch statement for string matching in JavaScript

That the way to use switch on strings is by sending the switch statement a "true" value.

What would be the most concise (and correct!) way to achieve this?

like image 460
J00MZ Avatar asked Aug 14 '13 10:08

J00MZ


1 Answers

OK, compiling both answers above my code that worked and was most elegant IMO is:

var fieldVal = $(this).val();

var msg;

switch (true) 
{
  case /Yes/.test(fieldVal):
      msg = "FOO";
      break;
  case fieldVal > 10 :
      msg = "BAR";
      break;
}

this works as separate if statements since we are evaluating whether or not the case returns true but in a clearer and more concise way that could give us the option to add totally disparate test statements in one switch.

the reason it works is probably that the case expression evaluated is interpreted as a true or false value and then checked against the main - switch(true)

like image 160
J00MZ Avatar answered Sep 23 '22 21:09

J00MZ