Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Joshua Earle
To check if a string is contained in an array, call the includes()
method,
passing it the string as a parameter. The includes
method will return true
if the string is contained in the array and false
otherwise.
const arr = ['one', 'two', 'three']; if (arr.includes('two')) { console.log('✅ String is contained in Array'); } else { console.log('⛔️ String is NOT contained in Array'); }
We used the
Array.includes
method to determine if the string two
is contained in the array.
The includes
method returns true
if the provided value is found in the array
and false
otherwise.
Note that the includes
method performs a case sensitive comparison.
If you need a case insensitive check whether a string is contained in an array, use the Array.some method instead.
const arr = ['one', 'two', 'three']; const two = 'TWO'; const containsString = arr.some(element => { return element.toLowerCase() === two.toLowerCase(); }); console.log(containsString); // 👉️ true
The function we passed to the some
method gets called with each element in the
array until it returns a truthy value or iterates over all array elements.
We convert both, the array element and the string to lowercase to perform case insensitive comparison.
If the function we passed to the some
method returns a truthy value at least
once, the method short-circuits and returns true
.
includes
method is not supported in Internet Explorer. If you need to support the browser, use the next approach covered in this article.To check if a string is contained in an array, call the indexOf
method,
passing it the string as a parameter. The indexOf
method returns the index of
the first occurrence of the string in the array, or -1
if the string is not
contained in the array.
const arr = ['one', 'two', 'three']; if (arr.indexOf('two') !== -1) { console.log('✅ String is contained in Array'); } else { console.log('⛔️ String is NOT contained in Array'); }
We use the
Array.indexOf
method to check if the string two
is contained in the array.
indexOf
method returns -1
, otherwise it returns the index of the first occurrence of the string in the array.This approach is definitely not as direct and readable as using the includes
method, however if you have to support Internet Explorer, it gets the job done.