admin管理员组

文章数量:1289390

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');

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');

Share Improve this question edited Mar 25, 2019 at 4:23 Smokey Dawson asked Mar 25, 2019 at 4:11 Smokey DawsonSmokey Dawson 9,24022 gold badges85 silver badges162 bronze badges 2
  • hello and james should both be in the string to be true? – Eddie Commented Mar 25, 2019 at 4:13
  • @Eddie more like or so in pseudo code string.includes('hello' || 'james'); – Smokey Dawson Commented Mar 25, 2019 at 4:14
Add a ment  | 

2 Answers 2

Reset to default 10

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 bo

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);

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"

本文标签: pass array to includes() javascriptStack Overflow