use of regex in a switch

0

I'm trying to use regular expressions to validate a switch, however, it occurs to me on the console that "day.match" is not a function:

function dayOfWeek(day){
   var regex = /[1-7]/g;
   if(!day.match(regex)){
      day == 8;
   }
   switch(day){
      case 1: return "Segunda";
      break;
      case 2: return "Terça";
      break;
      case 3: return "Quarta";
      break;
      case 4: return "Quinta";
      break;
      case 5: return "Sexta";
      break;
      case 6: return "Sábado";
      break;
      case 7: return "Domingo";
      break;
      case 8: return "Dia inválido";
      break;
   }
}

What's wrong, and how can I fix it?

    
asked by anonymous 20.10.2017 / 19:01

1 answer

2

The problem is that you might be trying to use match in a number , the correct one would be:

var regex = /[1-7]/;
if( !regex.test(day) ){
    day = 8;
}

Example

function dayOfWeek(day){
   var regex = /([1-7])/;
   if( !regex.test(day) ){
      day = 8;
   }

   switch(day){
      case 1: return "Segunda";
      break;
      case 2: return "Terça";
      break;
      case 3: return "Quarta";
      break;
      case 4: return "Quinta";
      break;
      case 5: return "Sexta";
      break;
      case 6: return "Sábado";
      break;
      case 7: return "Domingo";
      break;
      case 8: return "Dia inválido";
      break;
   }
}

console.log(dayOfWeek(5))
console.log(dayOfWeek(9))

In this way the regex will test whether the parameter is true or false . But your case does not use regex, you could use the default of switch :

function dayOfWeek(day){

    switch(day){
      case 1: return "Segunda";
      break;
      case 2: return "Terça";
      break;
      case 3: return "Quarta";
      break;
      case 4: return "Quinta";
      break;
      case 5: return "Sexta";
      break;
      case 6: return "Sábado";
      break;
      case 7: return "Domingo";
      break;
      default: return "Dia inválido";
      break;
   }
}

console.log(dayOfWeek(5));
console.log(dayOfWeek(9));
    
20.10.2017 / 19:31