Home > front end >  How to search through a string with an array of strings (js)?
How to search through a string with an array of strings (js)?

Time:12-23

What Im trying to do is the example below (except for the part where it doesnt work): I want to filter through a string (Message), where it checks for an array of strings (Exception), with outcome true (for any of the strings from the array) or false (if there are none of the strings from the array). I cant figure out how to make this work, as most information i find seems to do only the opposite (search through an array of strings with a single string).

Any help would be greatly appreciated!

var Message = "i bought a pear";
const Trigger = "bought";
const Exception = ["apple", "pear", "banana"]

if ((Message.includes(Trigger)) && (!Message.includes(Exception))) {
    console.log("Trigger hit!");                                         
}

CodePudding user response:

You need to iterate the exception array and check the message.

const
    message = "i bought a pear",
    trigger = "bought",
    exception = ["apple", "pear", "banana"];

if (message.includes(trigger) && !exception.some(e => message.includes(e))) {
    console.log("Trigger hit!");                                         
}

console.log(exception.some(e => message.includes(e))); // true

CodePudding user response:

    let message = "i bought a pear";
    const trigger = "bought";
    const exceptions = ["apple", "pear", "banana"];

    let newMessageArr = message.split(' ');
    exceptions.forEach((exception) => {
        console.log(exception);
        newMessageArr.forEach(word => {
            if( word === exception )
                console.log("true");
        })
    })
  • Related