0

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?

3
  • 2
    It sounds like you're looking for a case-insensitive comparison in JavaScript. Have you looked that up at all? Maybe .toLowerCase() everything as a first cut? Commented Mar 5, 2014 at 3:23
  • 1
    Make it all lower case with game.toLowerCase() Commented Mar 5, 2014 at 3:23
  • Does this answer your question? Case-insensitive switch-case Commented Aug 15, 2021 at 12:23

5 Answers 5

0

You can use String.toLowerCase() or String.toLocaleLowerCase()

game.toLowerCase();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

-1

Switch on a lower-cased version of the game:

switch (game.toLowerCase()) {
  case 'league of legends':
    console.log("You just played that!");
    break;
}

1 Comment

Thanks for the help. Almost everyone here knew exactly what I was talking about. I researched it but probably phrased it badly because I couldn't find exactly what I wanted. But this is exactly it thank you.
-1

String.toLowerCase()

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;
}

Comments

-1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.