0

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

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
jakewies
  • 342
  • 6
  • 18

2 Answers2

2

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.");
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Awesome so in essence I wrote double the code I needed to when i could simply end my prompt with .toLowerCase() . Appreciate it! – jakewies Mar 05 '15 at 06:39
2

Same as Arun's answer but shorter, you can use RegExp with i flag to ignore case:

if (/rock/i.test(userChoice)) {
  ...
}
aarosil
  • 4,848
  • 3
  • 27
  • 41
  • As I'm new to javascript and have only been exposed to the most basic techniques I'll have to read up on Regular expressions before implementing them so I have a clear understanding of their purpose. Appreciate the guidance! – jakewies Mar 05 '15 at 06:40
  • @JakeWiesler Yea they are very powerful and useful, figured I would give you the heads up and include link to API doc so you can read up on the goodness, enjoy! – aarosil Mar 05 '15 at 06:41