. Advertisement .
..3..
. Advertisement .
..4..
Are you experiencing trouble with make includes() case insensitive in JavaScript? Don’t worry about it! This article will explain what’s causing it, suggest some fixes, and assist you in selecting the one that will work best for your script. Let’s get going!
How to make includes() case insensitive in JavaScript?
Method 1: Convert all strings to the same case
We can convert all strings to the same case to use JavaScript includes() in a case-insensitive manner. The syntax of includes() is:
string.includes(searchvalue, start)
Parameters
searchvalue: Required. The string to search for.
start: Optional. The position to start from. Default value is 0.
Apply that method to reality, and we will have the program such as below:
// not assisted in IE 6-11
const str = 'CODING DRIVER';
const substr = 'coDiNg';
console.log(str.toLowerCase().includes(substr.toLowerCase())); //true
if (str.toLowerCase().includes(substr.toLowerCase())) {
// the string contains the substring
}
Method 2: Utilize the Array.filter methods
An array of all the elements that satisfy the criterion will be returned using this method. Simply lowercase each Array entry and the string, then run an equality check.
The syntax of Array.filter methods is:
array.filter(function(currentValue, index, arr), thisValue)
Parameters
function(): Required. A function to run for each array element.
currentValue: Required. The value of the current element
index: Optional. The index of the current element.
arr: Optional. The array of the current element.
thisValue: Optional. Default undefined. A value is passed to the function as its this value.
If we use that method in practice, we will get the following command and successfully answer the question of making includes() case insensitive in JS.
const arr = ['CODING', 'coDinG', 'DRIVER'];
const str = 'cOdIng';
const matches = arr.filter(element => {
return element.toLowerCase() === str.toLowerCase();
});
console.log(matches); // ['CODING', 'coDinG']
if (matches.length > 0) {
// at least 1 match found in array
}
Conclusion
We believe you’ve chosen wisely the method how to Make includes() case insensitive in JavaScript. ITtutoria hopes this clarifies the issue you encountered and possibly suggests a few other approaches to avoid it. If you have any severe problems with this bug, feel free to remark, and we’ll respond as quickly as possible! Thank you for reading.
Read more
→ How To Check If String Contains Specific Character in JavaScript
Leave a comment