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

问题描述 投票:2回答:3

我有一个问题的页面。用户必须在文本框中键入该问题的答案。我使用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>

我希望它接受以下所有答案是正确的,而不必添加额外的案例:

“超人”,“超人”,“超级男人”,“超级男人”,“超级男人!”,“超人”......

javascript switch-statement
3个回答
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;
}

2
投票

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

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
投票

用这个:

var desired = stringToReplace.replace(/[^\w\s]/gi, '').toLowerCase();
© www.soinside.com 2019 - 2024. All rights reserved.