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?
if/elsewould be the most concise and correct way, especially if there are only two cases. If there are additional cases then either add someelse ifbranches as needed or include all of the number cases first in aswitchand then do the regex tests in adefault. You can useswitch(true)and then put whatever conditions you like for eachcase, indeed I've done that myself, but it only tends to make the code shorter when there are fall-through cases...