0

help me please How to compare string and array if there string in array return true, else false string it in not one word, it is sentence

Here is my code

const keyWords = [
  "Hello",
  "hello",
  "help please",
  "Help please",
  "John",
  "john",
  "need",
  "Need"
]

var messageUser = "My name is Peter and I need help";

function check(str) {
  let newMessageUser = str.split(" ")

  for (let i = 0; i <= keyWords.length; i++) {
    for (let j = 0; j <= newMessageUser.length; j++) {
      let answer = (keyWords[i] === newMessageUser[j]) ? true : false;

      return answer
    }
  }
}

console.log(check(messageUser))
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes – Teemu Mar 29 '22 at 09:04
  • Are you trying to see if each word in `messageUser` is in `keyWords`? – Luminight Mar 29 '22 at 09:05
  • Does this answer your question? [How to check if a string contains text from an array of substrings in JavaScript?](https://stackoverflow.com/questions/5582574/how-to-check-if-a-string-contains-text-from-an-array-of-substrings-in-javascript) – pilchard Mar 29 '22 at 09:10

3 Answers3

1

you can use

  • array.some to check if one entry match a condition

  • string.includes to check if word is include in string

const keyWords = ["Hello", "hello", "help please", "Help please", "John", "john", "need", "Need"]

var messageUser = "My name is Peter and I need help";

function check(str) {
  return keyWords.some(word => messageUser.includes(word));
}

console.log(check(messageUser))
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
0

const keyWords = [
    "Hello",
    "hello",
    "help please",
    "Help please",
    "John",
    "john",
    "need",
    "Need"
]

const messageUser = "My name is Peter and I need help";

const results = keyWords.map((item) => {
    return messageUser.toLowerCase().includes(item.toLowerCase());
});

console.log(results);
Mamunur Rashid
  • 1,095
  • 17
  • 28
0

You can achieve that via single line of code.

const keyWords = [
  "Hello",
  "hello",
  "help please",
  "Help please",
  "John",
  "john",
  "need",
  "Need"
]

var messageUser = "My name is Peter and I need help";

console.log(keyWords.map(item => messageUser.includes(item)))
Debug Diva
  • 26,058
  • 13
  • 70
  • 123