Borislav Hadzhiev
Mon Oct 04 2021·3 min read
Photo by Bruno van der Kraan
To make the String.includes() method case insensitive in JavaScript, convert both of the strings you're comparing to lowercase.
// not supported in IE 6-11 const str = 'HELLO WORLD'; const substr = 'hELLo'; // 👇️ true console.log(str.toLowerCase().includes(substr.toLowerCase())); if (str.toLowerCase().includes(substr.toLowerCase())) { // 👉️ the substring is included in the string }
In the code example we've converted both - the string we call String.includes on and the substring to lowercase to make a case insensitive lookup.
To perform a case insensitive check whether a string is contained in an array:
Array.find
method, passing it a functionArray.find
method returns the first array element that satisfies the
conditionconst arr = ['HELLO', 'WORLD']; const str = 'HeLLo'; const found = arr.find(element => { return element.toLowerCase() === str.toLowerCase(); }); console.log(found); // 👉️ HELLO if (found !== undefined) { // 👉️ string is in array }
The function we passed to the Array.find method gets invoked with each element in the array until it returns a truthy value or iterates over all elements.
In the code example, the case insensitive check for the string succeeded and
Array.find
returned the corresponding array element.
If all of the invocations of the function we passed to Array.find
return a
falsy value, then the method returns undefined
.
Array.find
method stops iterating once its callback returns a truthy value, therefore it only returns the first match.If you need to perform a case insensitive check whether a string is contained in an array and get all matches:
Array.filter
method, passing it a functionArray.filter
method will return an array of all of the elements that
satisfy the conditionconst arr = ['HELLO', 'HeLlO', 'WORLD']; const str = 'HeLLo'; const matches = arr.filter(element => { return element.toLowerCase() === str.toLowerCase(); }); console.log(matches); // 👉️ ['HELLO', 'HeLlO'] if (matches.length > 0) { // 👉️ at least 1 match found in array }
The function we passed to the Array.filter method gets called with each element of the array.
Array.filter
method does not stop iterating once the callback function returns a truthy value and returns an array of all the elements that satisfy the condition.In our case two elements of the array satisfy the condition and we have both of their values in a brand new array.