【问题标题】:Finding multiple whole words with .split and .includes with Javascript使用 .split 和 .includes 使用 Javascript 查找多个完整的单词
【发布时间】:2021-11-25 19:06:00
【问题描述】:

我正在使用 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);
}

【问题讨论】:

    标签: javascript html split include


    【解决方案1】:

    您可以使用正则表达式:

    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
    

    要转义密钥,只需查看Is there a RegExp.escape function in JavaScript?

    【讨论】:

    • 感谢您的解释和链接!我很感激。我正在努力理解如何在我的代码中实现这一点。它应该看起来像: if (userInput.toLowerCase() .match(new RegExp('(^|\\s)'know'(\\s|$)')) .replace(/[.,\/# !$%\^&*;:{}=\-_`~ ()]/g,"") .split(/\s+/) .includes(key.toLowerCase())) {
    • 在你的情况下,变量“yourText”是“userInput.toLowerCase()”,而“youKeyRegexEscaped”是“key.toLowerCase()”(但如果你有一些特殊字符,比如“.” , "\", "[" 等,需要转义)。然后仅将其置于“如果”条件下。你不需要拆分任何东西
    • 只是:如果 (userInput.toLowerCase().match(new RegExp('(^|\\s)'+key.toLowerCase()+'(\\s|$)')) { hasKeyword = true; . . .
    猜你喜欢
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2012-03-26
    • 2016-08-05
    相关资源
    最近更新 更多