0

Working on a new chatbot and the chatbot looks to see if a single word matches. If it does, it displays the contents of a text file. For example: address - will display the address text file. However, if someone types "what's your address?" It responds with I don't understand.

Is there a way to look through a response and pick a keyword that matches what they may be asking.

Here is that example:

_processSay(message) {
        const address = this._address;
        const events = this._events;
        let content;
 
        if (message == 'address') {
        content = fs.readFileSync(address).toString();
        }
        
        else if (message == 'events') {
        content = fs.readFileSync(events).toString();
        }
 
        else {
        content = "sorry, I did not understand you";
        }
 
        return content;
        }

I'm totally new to javascript so I'm trying to work it out.

I was looking for a containsor includes rather than == type statement. I haven't found one as yet but live in hope

  • You can use `message.includes('address')` to check if the string contained the substring `"address"` in it. – Unmitigated Mar 08 '23 at 16:54
  • [String.includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) or [regex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) – Dave Newton Mar 08 '23 at 16:54

1 Answers1

0

You can use String#includes. For case insensitive searching, convert the message to lower case first with message = message.toLowerCase().

if (message.includes('address')) {
    // ...
} else if (message.includes('events')) {
    // ...
} else {
    // ...
}

If you want to only match separate words rather than just substrings, you can use regular expression word boundaries.

if (/\baddress\b/i.test(message)) {
    // ...
} else if (/\bevents\b/i.test(message)) {
    // ...
} else {
    // ...
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80