I have a node.js script where I want to find if a given string is included inside an array. how can I do this?
Thanks.
If I understand correctly, you're looking for a string within an array.
One simple way to do this is to use the indexOf()
function, which gives you the index a string is found at, or returns -1 when it can't find the string.
Example:
var arr = ['example','foo','bar'];
var str = 'foo';
arr.indexOf(str); //returns 1, because arr[1] == 'foo'
str = 'whatever';
arr.indexOf(str); // returns -1
Edit 19/10/2017
The introduction of ES6 gives us :
arr.includes('str') //true/false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With