Note. You are using test() incorrectly, this is a regular expression object method, so you need /Yes/.test(field) , not field.test('Yes') . Anyway...
If you have only two cases, as shown, I would use the if/else/else if structure:
var field = $(this).val(); var msg; if(/Yes/.test(field)) { msg = "FOO\n"; } else if (field === 10) { msg = "BAR\n"; }
If you need to add additional cases, I will simply add additional if else {} branches at the end.
If you have several specific numeric cases, you can put them in a switch using the regex tests at the end of default at the end:
switch (field) { case 10: msg = "BAR\n"; break; case 30: msg = "whatever\n"; break; case 50: msg = "hi\n"; break; default: if (/Yes/.test(field)) { msg = "FOO\n"; else if (/No|N|False|/i.test(field)) { msg = "blah\n"; } break; }
The switch (true) option you are referring to in the question is actually just a more messy version of if/else/else if , so that doesn't make sense if you don't have some errors:
switch(true) case /Yes/.test(field): case /Y/.text(field): case /Whatever/.text(field): msg = "FOO\n"; break; case field == 10: msg = "BAR\n"; break; }
... and even then a if with several conditions related to || may be exactly the same neat with the appropriate newlines, and combining multiple regular expressions into one of them is probably a lot neater.
source share