I’m trying to manage my if statements into a switch statement to evaluate regex, but I don’t know how I can go about it. I tried many possibilities but cannot do it. See code below, is it right?:
var username = $('input.username'),
phone = $('input.phone'),
numRegex = /^[0-9]/i,
alphaRegex = /^[a-zA-Z]/i,
usernameVal = username.val(),
phoneVal = phone.val();
switch (phoneVal) {
case numRegex.test(phoneVal):
console.log('Only digits please.');
break;
default:
console.log('It\'s all good.');
}
Many thanks.
I think this kind of defeats the point of the
switchstatement having the conditions in thecasestatements. It’s intent is to test multiple outputs given a single input.Perhaps if JavaScript supported multiple inputs (or destructuring of arrays) in a
switch..caseI could see something like this:But alas, I’d say sticking with
if..elseis a better and easier to follow/understand option, in this case: