Javascript: check if an array contains a string
- Authors
- Name
- Hamza Rahman
- Published on
- -2 mins read-
Two related questions come up a lot, and they are the reverse of each other. This post covers both: checking whether an array contains a given string, and checking whether a string contains any element from an array.
Check if an array contains a string
The cleanest way is Array.prototype.includes(), which returns true or false.
const fruits = ['apples', 'grapes', 'watermelons', 'mangoes']
fruits.includes('grapes') // truefruits.includes('pizza') // falseIf you also need the position, use indexOf. It returns the index, or -1 when the value is not found.
fruits.indexOf('grapes') // 1fruits.indexOf('pizza') // -1fruits.indexOf('grapes') !== -1 // trueFor a case-insensitive check, or to match on part of each entry, use .some() with your own test.
const hasGrapes = fruits.some((fruit) => fruit.toLowerCase() === 'grapes')Check if a string contains any array element
This is the inverse: given a sentence and a list of words, is any word in the sentence? The .some() method paired with String.prototype.includes() does it in one line.
const stringTODO = 'bring some apples for guests'const stringTODOFalsely = 'bring pizza for guests'const basket = ['apples', 'grapes', 'watermelons', 'mangoes']
const hasFruit = basket.some((fruit) => stringTODO.includes(fruit))const hasPizza = basket.some((fruit) => stringTODOFalsely.includes(fruit))
console.log('hasFruit:', hasFruit, '\nhasPizza:', hasPizza)Output:
hasFruit: truehasPizza: false.some() runs the test for each array element and returns true as soon as one matches, so stringTODO.includes(fruit) checks whether the sentence contains that word.
Related articles
Check if a string is alphanumeric in JavaScript
How to check if a string is alphanumeric in JavaScript using a regular expression, including a reusable helper and notes on empty strings and Unicode.
Force an LLM to return JSON in JavaScript
Reliably get JSON from an LLM in JavaScript with OpenAI structured outputs and a Zod schema, instead of prompting for JSON and parsing fragile model text yourself.
The nullish coalescing operator (??) in JavaScript
What the double question mark (??) means in JavaScript: the nullish coalescing operator, how it differs from ||, and the ??= assignment shorthand.

