Search code examples
javascriptcase-insensitive

Case-insensitive in JavaScript


In the following code, a user is expected to enter "rock", "paper", or "scissors" in the userChoice prompt.

However, if a user enters any of those three words partially or entirely in upper-case, as in "ROCK", "Paper", or "sCissORs", will the program run the else portion of the code and an alert message pop up?

If so, is it possible to tell the computer that case does not matter as long as "rock", "paper", or "scissors" is entered?

var userChoice = prompt("Do you choose rock, paper or scissors?");

if (userChoice === "rock" || userChoice === "paper" || userChoice === "scissors") {
// NOTHING
}
else {
    alert("Please enter a VALID word.");
}

Solution

  • change it to (making sure that it is lower case before comparison)

        var userChoice = prompt("Do you choose rock, paper or scissors?");
        userChoice = userChoice.toLowerCase();
       var choices= ["rock", "paper", "scissors"];
        if (choices.indexOf(userChoice)) {
        // NOTHING
        }
        else {
            alert("Please enter a VALID word.");
        }