0

I am currently doing a quiz in JavaScript and would like it so that the user could type using lowercase or uppercase but it does not effect the result. I have had a look about but I'm struggling to see anything that could help. (I know to add a question, and of course the correct answer - which I am currently developing). Thank you.

function Quiz()
{
    var answer = prompt("question here?","");
    if (answer=="your answer here")
    {
    alert ("Correct!");
    }
    else 
    alert ("Incorrect");
}
  • 3
    `answer = answer.toLowerCase()` then compare everything in lowercase. – elclanrs Jan 18 '14 at 22:58
  • possible duplicate of [JavaScript case insensitive string comparison](http://stackoverflow.com/questions/2140627/javascript-case-insensitive-string-comparison) – SOReader Jan 18 '14 at 23:01

2 Answers2

1

You can convert both sides to lower case by using String.prototy.toLowerCase() function. This will insure that both strings are lower case.

function Quiz()
{
    var answer = prompt("question here?","");
    if (answer.toLowerCase()=="your answer here".toLowerCase())
    {
    alert ("Correct!");
    }
    else 
    alert ("Incorrect");
}
Epsil0neR
  • 1,676
  • 16
  • 24
1

You want to call String.prototype.toLowerCase on answer. This converts everything with lower case letters so you can compare easily:

if (answer.toLowerCase().trim() == "your answer here".toLowerCase()) {
    // ...
}

The trim function removes trailing and leading whitespace in case the user accidentally enters some.

Cu3PO42
  • 1,403
  • 1
  • 11
  • 19
  • but what will happen when right side will contain some uppercase? your comparison will always fail, in that case you should convert both sides – Epsil0neR Jan 18 '14 at 23:18
  • Absolutely valid point, I was admittedly just copying the string for the answer and saw it was lower case, so there was no need to explicitly convert it. If you have any variable you must convert that as well, of course. – Cu3PO42 Jan 18 '14 at 23:23