我正在使用 javascript 和 html 来开发一个简单的聊天机器人。下面的代码有效并使用 .split 来检查整个单词,但是,这意味着输入的任何内容都比一个单词长,例如“你好吗?” 不再有效。如何改变这一点,以便它允许多个单词,但仍然检查像“hi”这样的整个单词,这样它们就不会被更大的单词(例如“high”等)接收到。
任何帮助将非常感激!谢谢!
var know = {
<!--General Phrases-->
"Hi": "Hello! 👋",
"Hey": "Hello! 👋",
"Hello":"Hello 👋 How can I help?",
"how are you":"Not bad, thanks!",
"Bye":"Have a nice day!",
"Goodbye":"See you later!",
<!--Directory-->
"Help": `You can find help by searching below or by clicking <a href='https://www.page.com/news' target="_blank">here</a>`,
"contact": `You can contact us by clicking <a href='https://www.page.com/contact' target="_blank">here</a>`,
"About": `You can find our About Us page by clicking <a href='https://www.page.com/about' target="_blank">here</a>`
};
function goo() {
var userBox = document.getElementById('userBox');
var userInput = userBox.value;
var chatLog = document.getElementById('chatLog');
var chatLogContent = "";
if (!userInput) {
chatLogContent = ''
}
var hasKeyword = false;
for (var key in know) {
if (userInput.toLowerCase()
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~ ()]/g,"")
.split(/\s+/)
.includes(key.toLowerCase())) {
hasKeyword = true;
break;
} else {
hasKeyword = false;
}
}
if (hasKeyword) {
chatLogContent += know[key] + "<br>"; //or use know.key
} else {
chatLogContent += "No results found. Please enter another search term below.<br>";
}
var server = document.createElement('div');
server.setAttribute('class', 'server');
server.innerHTML = chatLogContent;
document.getElementById('chatLog').innerHTML = '';
chatLog.appendChild(server);
}
您可以使用正则表达式:
var yourText = "how are you";
var youKeyRegexEscaped = "how are you"
yourText.match(new RegExp('(^|\\s)'+youKeyRegexEscaped+'(\\s|$)'))
Rexgex 解释:
(^|\s) -> begining of the string or space
(\s|$) -> space or end of string
要转义密钥,只需查看JavaScript中是否有 RegExp.escape 函数?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句