EN
JavaScript - check if array of strings contains given string
0 points
In this article, we would like to show you how to check if an array of strings contains a given string using JavaScript.
Quick solution:
xxxxxxxxxx
1
var letters = ['a', 'b', 'c'];
2
3
var letter = 'b'; // string to search for
4
5
if (letters.indexOf(letter) > -1) {
6
// do some action when string is in array e.g:
7
console.log('The letter is in the array.');
8
} else {
9
// do some action when string is not in array e.g:
10
console.log('The letter is not in the array.');
11
}
In this example, we create a reusable arrow function to check if string
is in the array
.
xxxxxxxxxx
1
const isInArray = (array, string) => {
2
if (array.indexOf(string) > -1) {
3
return true;
4
}
5
return false;
6
};
7
8
9
// Usage example:
10
11
var letters = ['a', 'b', 'c'];
12
13
console.log(isInArray(letters, 'a')); // true
14
console.log(isInArray(letters, 'x')); // false