4

I have a page with a question. The user will have to type the answer to that question in a textbox. I am using a switch statement to generate different feedback to different answers. I already managed to make it case insensitive.

Is there a way to also make it ignore punctuation and spaces?

This is the code I have:

function myFunction() {
    var text;
    var answers = document.getElementById("myInput").value.toLowerCase();
    switch (answers) {
        case "superman":
            text = "That is correct!";
            break;
        case "batman":
            text = "You must be kidding me...";
            break;
        default:
            text = "Wrong answer."
    }
    document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>

I would like it to accept all the following answers as correct, without having to add extra cases:

"Superman", "superman", "Super Man", "Super man", "Super-Man!", "Super-man"...

MikeMichaels
  • 454
  • 1
  • 6
  • 25
  • possible duplicate of https://stackoverflow.com/questions/4374822/remove-all-special-characters-with-regexp – Aagam Jain Sep 18 '18 at 10:25

3 Answers3

4

You could use a regex to ignore everything else that is not an alphabet.

function myFunction() {
    var text;
    var answers = document.getElementById("myInput").value.toLowerCase();
    answers = answers.replace(/[^a-z]/g, "");
    switch (answers) {
        case "superman":
            text = "That is correct!";
            break;
        case "batman":
            text = "You must be kidding me...";
            break;
        default:
            text = "Wrong answer."
    }
    document.getElementById("comment").innerHTML = text;
}
Saransh Kataria
  • 1,447
  • 12
  • 19
3

You could match only letters and omit unwanted character. Then take convert to lower case.

function myFunction() {
    function getLetters(s) { return s.match(/[a-z]/gi).join('').toLowerCase(); }

    var text;
    var answers = document.getElementById("myInput").value.toLowerCase();
    switch (getLetters(answers)) {
        case "superman":
            text = "That is correct!";
            break;
        case "batman":
            text = "You must be kidding me...";
            break;
        default:
            text = "Wrong answer."
    }
    document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

use this:

var desired = stringToReplace.replace(/[^\w\s]/gi, '').toLowerCase();
Aagam Jain
  • 1,546
  • 1
  • 10
  • 18