use of regex on a switch

Asked

Viewed 51 times

0

I’m trying to use regular expressions to validate a switch, but 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 ?

  • Check the "day", the message is stating that the match does not exist in the "day", it is possible that you are sending something wrong in the "day".

  • just as is my question, how will I check if I do not know what this can mean ?

  • So put console.log(day), and see on the console what’s coming in "day"

  • his var day is an instance of the object Date?

  • is not @Guilhermelautert , only one day entered by user

1 answer

2


The problem is that you may be trying to use match in a number, the correct 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))


This way the regex will test whether the parameter is true or phony. But your case waives the use of regex, could use the default 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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.