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');
-
hello
andjames
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
2 Answers
Reset to default 10Based 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
版权声明:本文标题:pass array to includes() javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741473351a2380738.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论