Search code examples
javascriptcontains

How can Javascript action a response based on a keyword in a phrase instead of just a single word?


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


Solution

  • 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 {
        // ...
    }