Reputation: 9230
I'm trying to find out if a string includes multiple strings stored in array with .includes()
So I've tried
let string = 'hello james';
console.log(string.includes(['hello', 'james']));
but it is being returned as false
.. when I know the string includes 'hello' or 'james' is this even possible?? how can I tell if a string contains either the word 'hello' or 'james'
So in pseudo code this would look like string.includes('hello' || 'james');
Upvotes: 3
Views: 7728
Reputation: 1018
According to the documentation, the str.includes
takes a string
as the first parameter.
So when you pass an array instead, it converts the array of strings to a single string, and uses that string as the first parameter of the includes function.
Just to demonstrate this point,
let string = "hello,james";
var array = ["hello", "james"]
console.log(string.includes(array)); // returns true, as array would be converted to "hello,james"
Upvotes: 1
Reputation: 26844
Based on the docs, includes
first parameter is a string and not an array.
You can do:
If you want to check if each and every string in the array is present on the string, you can use every
and includes
combo
let string = 'hello james';
let toCheck = ['hello', 'james'];
let result = toCheck.every(o => string.includes(o));
console.log(result);
You can use some
instead of every
if you want to check at least one entry in the array is present on the string.
let string = 'hello james';
let toCheck = ['hello', 'james1'];
let result = toCheck.some(o => string.includes(o));
console.log(result);
Upvotes: 10