使用 .split 和 .includes 使用 Javascript 查找多个完整单词

比尔柯林斯

我正在使用 javascript 和 html 来开发一个简单的聊天机器人。下面的代码有效并使用 .split 来检查整个单词,但是,这意味着输入的任何内容都比一个单词长,例如“你好吗?” 不再有效。如何改变这一点,以便它允许多个单词,但仍然检查像“hi”这样的整个单词,这样它们就不会被更大的单词(例如“high”等)接收到。

任何帮助将非常感激!谢谢!

var know = {
<!--General Phrases-->  
"Hi": "Hello! &#128075",
"Hey": "Hello! &#128075",
"Hello":"Hello &#128075 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Array.includes()和测试重复项的JavaScript问题

使用 postgres 和 javascript 搜索多个单词

使用 .includes 查找子数组

javascript split()使用regEx

使用preg_split分割和弦和单词

Javascript:使用`.includes`查找对象数组是否包含特定对象

使用或检查多个Array.includes

如何使用.includes按多个值过滤?

如何使用javascript和regex查找“ mergefields”?

使用 javascript 刷新、查找和提醒

Javascript的.includes函数无法正确使用对象数组

javascript - 使用带有单词和结果的多个方程不断出错

使用GREP选择多个单词和字符

使用fgrep查找多个单词(korn shell)

Excel:使用查找矩阵替换多个单词

如何在javascript中使用split函数和RegEx按长度分割字符串?

在Python中使用.split()和.join()

Logstash-使用mutate和split

使用.split()和.include(的SQL查询

使用此.length和.split()的替代方法?

如何使用Array.prototype.includes()查找对象?

使用 JavaScript regex 在方括号(和前面的文本)中查找多个值

JavaScript .includes()方法的多个条件

使用 javascript split 函数两次

如何使用 split 从字符串内的单词中拆分逗号和句点?

使用.split()和.filter()方法从数组字符串中删除单词

如何使用split和for循环在列表中提取单词而不是字符?

在Rmarkdown和knitr中同时使用in_header和header_includes

使用多个参数查找和 grep