Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Ignore punctuation and spaces in a Switch Statement

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"...

like image 755
MikeMichaels Avatar asked Oct 19 '25 02:10

MikeMichaels


2 Answers

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;
}
like image 83
Saransh Kataria Avatar answered Oct 21 '25 15:10

Saransh Kataria


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>
like image 42
Nina Scholz Avatar answered Oct 21 '25 16:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!