Compare strings without being case-sensitive

3.2k views Asked by At

I have problem with a variable I made (it's a string) in JavaScript. It will be prompt from the user and then with the switch I will check if it is true or not. Then when I input it upper case it will say it is identified as a another var.

Here is my code:

var grade = prompt("Please enter your class") ;

switch ( grade ){
    
    case "firstclass" :
         alert("It's 500 $")
         break;
    case "economic" :
         alert("It's 250 $")
         break;
    default:
         alert("Sorry we dont have it right now");

}

4

There are 4 answers

0
iam-decoder On BEST ANSWER

as @nicael stated just lowercase what they input. However, if you need to preserve the way it was input and only compare using the lowercase equivalent, use this:

var grade = prompt("Please enter your class") ;

switch ( grade.toLowerCase() ){

  case "firstclass" :
     alert("It's $500");
     break;
  case "economic" :
     alert("It's $250");
     break;
  default :
     alert("Sorry we don't have it right now");
}
0
nicael On

Just lower case it initially.

var grade = prompt("Please enter your class").toLowerCase() ;
0
Richard Kho On

You could set the entire string to lower case by using the String prototype method toLowerCase() and compare the two that way.

To keep the input the same, mutate the string during your switch statement:

switch( grade.toLowerCase() ) {
  // your logic here
}
0
King Clauber On

You should always compare uppercase string with uppercase values in case sensitive languages.
Or lower with lower.

var grade = prompt("Please enter your class") ;

switch (grade.toUpperCase())
{    
case "FIRSTCLASS" :
     alert("It's 500 $")
     break;
case "ECONOMIC" :
     alert("It's 250 $")
     break        ;
default   :
     alert("Sorry we dont have it right now");
}