Javascript 如何使开关大小写忽略字符串中的标点符号?
我有一个Javascript 如何使开关大小写忽略字符串中的标点符号?,javascript,html,Javascript,Html,我有一个,在那里我键入了一些东西,然后我收到了下面的答案,具体答案取决于我键入的内容。当我用标点符号写作时,我发现了一个问题,它没有给我预期的答案。如何使开关盒忽略标点符号 这是我的密码: <button onclick="myFunction()">Try it</button> <textarea id="box" rows="4" cols="50"></textarea> <p id="output"></p>
,在那里我键入了一些东西,然后我收到了下面的答案,具体答案取决于我键入的内容。当我用标点符号写作时,我发现了一个问题,它没有给我预期的答案。如何使开关盒忽略标点符号
这是我的密码:
<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>
试试看
函数myFunction(){
var text=document.getElementById(“输出”);
var str=document.getElementById(“box”).value.toLowerCase();
开关(str){
case“hi”:text.innerHTML=“你好!”;
case“hello”:text.innerHTML=“hello,hello!”;break;
案例“早上好”:text.innerHTML=“早上好,朋友!”;休息;
案例“晚上好”:text.innerHTML=“晚上好,先生!”;休息;
违约:
text.innerHTML=“我不知道说什么。试着说‘你好’或‘你好’。”休息;
}
}
解决方案是在将字符串传递到交换机之前删除字符串中的所有标点符号:
输出:
Hello,hello!
顺便说一句:在您的特定情况下,我会使用对象而不是开关盒:
switch/case进行精确比较,您无法更改其行为。虽然可以调整输入字符串,但在将字符串传递到开关之前,只需删除字符串中的所有标点符号即可。将字符串小写可能也是个好主意。我解决了它。感谢您的建议@АццБццццццц。
Hello,hello!
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;