Search code examples
javascriptif-statementvariablespromptcase-sensitive

How to ignore case when dealing with a variable in an if statement - Javascript


Am a complete beginner in Javascript and trying to use as simple as code as possible. Having some issues regarding case sensitivity when it comes to using a variable from a prompt inside an if statement. Here is the code in question. It works perfectly assuming the input is exactly 'French'

if (number => 1 && number <= 30) {
    var lang= prompt ("Which language do you want to translate into, French or German?");
}
while(lang != "French" && lang != "french" && lang != "FRENCH" && lang != "German" && lang != "german" && lang != "GERMAN" ) {
    alert("Only French or German is allowed");
    var lang= prompt ("Which language do you want to translate into, French or German?");
}   


    if (number == 1 && lang == "French") {
        alert("The translation is " +frenchNumbers[1]);
    }
    if (number == 2 && lang == "French") {
        alert("The translation is " +frenchNumbers[2]);
    }
    if (number == 3 && lang == "French") {
        alert("The translation is " +frenchNumbers[3]);
    }

I want the 'if' statements to also work if the user was to enter 'french' or 'FRENCH'. I have tried to use the next piece of code, but it cycles through the alerts from the beginning, which is not what I want. For example if I was to enter '3' and 'FRENCH' I would get the alerts for '1' and '2' first.

if (number == 1 && lang == "French" || lang == "french" || lang == "FRENCH") {
        alert("The translation is " +frenchNumbers[1]);
    }
    if (number == 2 && lang == "French" || lang == "french" || lang == "FRENCH") {
        alert("The translation is " +frenchNumbers[2]);
    }
    if (number == 3 && lang == "French" || lang == "french" || lang == "FRENCH") {
        alert("The translation is " +frenchNumbers[3]);
    }

I'm sure there's an easy work around, going a little crazy trying to work it out as all the information I've looked at is well above my skill level

Any help would be great

Thanks, Brad


Solution

  • As explained by Chris Baker, you can use .toLowerCase(). The code you need to adjust is as follows.

    while(lang.toLowerCase() != "french" && lang.toLowerCase() != "german") {
    ...
    if (number == 1 && lang.toLowerCase() == "french") {
    ...