Search code examples
javascriptconditional-statementsprompt

I need to validate an input regardless of text capitalization


I have written a short script that works pretty much as a quiz. It displays a dialogue box making a question and you input the answer. However, my intention is that whether the answers are provided in capital or lowercase text, the app should grant you a point regardless. My question is, how can I give a point regardless of text capitalization of the input? I saw someone using toUpperCase() at some point in the code, but I am not quite sure.

let questions = [
  ["Who created Demon Slayer?", 'Gotouge'],
  ['Who was the first demon that ever existed?', 'Muzan'],
  ['Who was the flame pillar of the Demon Slayer Corps?', 'Rengoku']
];


let item = '';
let score = 0;

function quiz (arr){
  for (let i = 0; i<questions.length; i++){
    let interrogate = prompt(`${arr[i][0]}`);
    if(interrogate === arr[i][1]){
      score++;
    }
  }
}


quiz(questions);
console.log(score);

Solution

  • This should be what you want, I simplify your code a little bit.

    I also add trim() to remove white space in the end and begining.

    let questions = [
      ["Who created Demon Slayer?", 'Gotouge'],
      ['Who was the first demon that ever existed?', 'Muzan'],
      ['Who was the flame pillar of the Demon Slayer Corps?', 'Rengoku']
    ];
    
    let score = 0;
    function quiz (arr){
      for (let i = 0; i<questions.length; i++){
        let interrogate = prompt(`${arr[i][0]}`);
        if(interrogate.trim().toLowerCase() === arr[i][1].toLowerCase()) score++;  
      }
    }
    quiz(questions);
    console.log(score);