Search code examples
javascriptif-statementpromptcapitalizationcapitalize

Simplifying IF statement when comparing userInput from a prompt


I'm writing a simple Rock, Paper, Scissors program from scratch and I have an IF statement that seems bloated. I know it can be trimmed down but I can't find the answer anywhere.

I first get a variable userChoice by prompting the user to input their response from this statement:

var userChoice = prompt("Choose either Rock, Paper, or Scissors.");

I would like the program to accept capitalized and uncapitalized responses (rock or Rock would be valid), and I would also like to alert the user when their response is invalid.

Is there a way to accept uncapitalized and capitalized responses (rock or Rock) without writing a bloated IF statement such as mine?

if (userChoice !== "Rock" && userChoice !== "rock") {
    alert("Invalid response.");
}

This IF statement is shortened. In my actual code the IF statement runs on comparing uncapitalized and capitalized versions of paper and scissors as well. But for sake of the example I left all the nonsense out.

Thanks


Solution

  • convert the user input userChoice to lower/upper case and then compare with a lower cased string like

    var userChoice = prompt("Choose either Rock, Paper, or Scissors.").toLowerCase();
    
    if (userChoice !== "rock") {
        alert("Invalid response.");
    }