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))
CodePudding user response:
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))
CodePudding user response:
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);