Javascript-忽略Switch语句中的标点和空格

时间:2018-09-18 10:23:28

标签: javascript switch-statement

我有一个问题页面。用户将必须在文本框中键入该问题的答案。我正在使用switch语句来生成对不同答案的不同反馈。我已经设法使其不区分大小写。

有没有办法让它忽略标点和空格?

这是我的代码:

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>

我希望它接受以下所有正确答案,而不必添加其他情况:

“超人”,“超人”,“超人”,“超人”,“超人!”,“超人” ...

3 个答案:

答案 0 :(得分:3)

您可以使用正则表达式忽略所有不是字母的内容。

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;
}

答案 1 :(得分:2)

您只能匹配字母并省略不需要的字符。然后将convert转换为小写。

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>

答案 2 :(得分:2)

使用此:

var desired = stringToReplace.replace(/[^\w\s]/gi, '').toLowerCase();