0
const exampleArray = [
  "Can't predict now",
  "Concentrate and ask again",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful"
]


for (i = 0; i < responses.length; i++) {
    if (responses[i].includes("no")) {
        alert(`hit at ${responses[i]}`)
    } 
}

I'm trying to write a program that will search through an array and find any instances of "no" in the strings in the array. The issue is I'm also detecting instances of "not" or "now" when all I want is instances of "no" specifically.

  • You need to use a reg exp with word boundries. https://stackoverflow.com/questions/2232934/how-can-i-match-a-whole-word-in-javascript – epascarello Nov 11 '22 at 17:41
  • Can you please elaborate on your question and also add an example array in which you are searching? – Tarun Kumar Sao Nov 11 '22 at 17:44
  • I added an example array. The end goal is to delete any strings out of the array that include the word "no" but its also detecting strings that include "not" and "now" which is the issue –  Nov 11 '22 at 17:54
  • How is "no" not matched in "not"? If you want to match whole words, why don't you say so anywhere in the question? – Barmar Nov 11 '22 at 18:07
  • something very similar i got https://stackoverflow.com/questions/74393899/detecting-a-specific-word-in-a-message-in-discord-js/74394327#74394327 – cmgchess Nov 11 '22 at 18:07
  • A simple regex will do the trick. -- const filteredArray = exampleArray.filter((str) => str.match(/\b(no)\b/g)); – Harshal Limaye Nov 11 '22 at 18:12

2 Answers2

0

There are several approaches to this problem, I would use Regular Expressions combined with String.Match() to solve this problem.

Take a look at the String.Match() method, it may solve your problem:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

0

Try this method that I have just done.

const array = ["Now we", "We say no", "They do not"];

//we loop through the array
array.forEach((sentence) => {
  //Switch to lower case and split the sentence
  splitSentence = sentence.toLowerCase().split(" ");

  //we loop through the split sentence
  splitSentence.forEach((word) => {
    //we check if it is equal to 'no'
    if (word == "no") {
      console.log(sentence);
    }
  });
});