Estoy usando javascript y html para desarrollar un chatbot simple. El siguiente código funciona y usa .split para verificar una palabra completa, sin embargo, esto significa que cualquier cosa ingresada más larga que una palabra, como "¿cómo estás?" ya no funciona ¿Cómo se puede cambiar esto para que permita varias palabras pero aún verifique palabras completas como "hola" para que no se recojan en palabras más grandes como "alto", etc.
¡Cualquier ayuda sería muy apreciada! ¡Gracias!
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); }Puedes usar la expresión regular:
var yourText = "how are you"; var youKeyRegexEscaped = "how are you" yourText.match(new RegExp('(^|\\s)'+youKeyRegexEscaped+'(\\s|$)'))Explicación de Rexgex:
(^|\s) -> begining of the string or space (\s|$) -> space or end of stringPara escapar de la clave, solo mire ¿Existe una función RegExp.escape en JavaScript?