如何使switch case忽略字符串中的标点符号?

时间:2016-03-23 18:20:31

标签: javascript html

我有<textarea>我输入的内容我在下面收到,具体的答案取决于我输入的内容。当我用标点符号写字时,我发现了一个问题,它并没有给我预期的答案。如何使switch case忽略标点符号?

这是我的代码:

<button onclick="myFunction()">Try it</button>

<textarea id="box" rows="4" cols="50"></textarea>
<p id="output"></p>

<script>
function myFunction() {
var text = document.getElementById("output");
var str = document.getElementById("box").value.toLowerCase();
switch(str){
case "hi": text.innerHTML = "Hi there!";break;
case "hello": text.innerHTML = "Hello,hello!";break;
case "good morning":  text.innerHTML = "Good morning, pal!";break;
case "good evening":  text.innerHTML = "Good evening, sir!";break;
default:
text.innerHTML = "I don't know what to say. Try to say 'hello' or 'hi'.";break;

}
}
</script>

1 个答案:

答案 0 :(得分:1)

解决方法是在将字符串传递给开关之前从字符串中删除所有标点符号:

run code

var input = "H.E,L:;!?L()[o]{}";
// You can add more punctuation into the regex if you need 
var str = input.toLowerCase().replace(/[.,:;!?(){}\[\]]+/g, '');
var result;
switch(str){    
    case "hi": result = "Hi there!";break;
    case "hello": result = "Hello,hello!";break;
    case "good morning": result = "Good morning, pal!";break;
    case "good evening": result = "Good evening, sir!";break;
    default:
    result = "I don't know what to say. Try to say 'hello' or 'hi'.";break;
}

输出:

Hello,hello!

BTW:在你的具体情况下,我会使用一个对象而不是一个switch-case:

run code

var responses = { 
    hi: "Hi there!",
    hello: "Hello,hello!",
    "good morning": "Good morning, pal!",
    "good evening": "Good evening, sir!"
};
var default_response = "I don't know what to say. Try to say 'hello' or 'hi'.";

var input = "H.E,L:;!?L()[o]{}";
var key = input.toLowerCase().replace(/[.,:;!?(){}\[\]]+/g, '');
var result = key in responses ? responses[key] : default_response;