I want a method that finds a word in a string, it have to be a whole array, not subarray on a string(as array.includes() does)
const key = ['one','two','three']
let message = 'onepiece'
key.forEach((j) => {
//string.prototype.includes()
if(message.includes(j)) console.log('Method1',true); //In this way is true always there is a 'one', no matter if the string is just 'one' or 'onepiece' or 'one piece'
else console.log('Method1',false)
//array.prototype.includes()
if(j.includes(message)) console.log('Method2',true); //In this way is true when message = 'one'
else console.log('Method2',false)
});
The following code does what I want
const key = ['one','two','three']
let message = 'one'
for (var i=0 ; message[i]!=undefined ; i++){
mes = message.split(" ")[i]
if(key.includes(mes)) console.log(true) //In this way is true when the message contains 'one', no matter if it's alone or in a string, but false if it's 'onepiece'
}
I feel this code is highly inefficient, my question is there a simpler way to do this function?
Thx!
Sounds like you are looking for intersection between two arrays since you are treating messsage as an array by splitting it. In that case you could use array.some() to check if any words in key exist in message:
const key = ['one', 'two', 'three']
let message = 'one'
let mes = message.split(' ')
let result = key.some(val => mes.includes(val))
console.log(result)
//Result is true for 'one'
//Result is true for 'one piece'
//Result is false for 'onepiece'