Reputation: 75
I'm making a simple switch
function:
var game = prompt("What game do you want to play?");
switch(game) {
case 'League of Legends':
console.log("You just played that!");
//more case statements snipped... //
break;
}
If the user puts league of legends
, not League of Legends
would it catch that or would it reset to the default answer at the bottom of all my cases? Furthermore, how would I change it so both answers, capitalized and not, worked?
Upvotes: 1
Views: 6255
Reputation: 2996
The string 'league of legends' and 'League of Legends' are different so that would fall to the default at the bottom of all your cases.
To make it work, you may use
switch(game.toUpperCase()) {
case 'LEAGUE OF LEGENDS':
console.log("You just played that!");
//more case statements snipped... //
break;
}
Upvotes: -1
Reputation: 837
In javascript the character 'L' doesn't equal the character 'l'. Therefore 'League of Legends' wouldn't match 'league of legends'. By converting the users input to all lowercase and then matching it to a lowercase string in your switch statement, you can guarantee your program won't discriminate based on case.
Your code with toLowerCase()
var game = prompt("What game do you want to play?");
game = game.toLowerCase();
switch(game) {
case 'league of legends':
console.log("You just played that!");
//more case statements snipped... //
break;
}
Upvotes: -1
Reputation: 43718
String compare is case-sensitive, therefore you should either upper-case everything using yourString.toUpperCase()
or lowercase with yourString.toLowerCase()
if your code needs to be case-insensitive.
Upvotes: 0
Reputation: 4865
You can use String.toLowerCase() or String.toLocaleLowerCase()
game.toLowerCase();
Upvotes: 0
Reputation: 36438
Switch on a lower-cased version of the game:
switch (game.toLowerCase()) {
case 'league of legends':
console.log("You just played that!");
break;
}
Upvotes: -1