Open In App

JavaScript- Make Array.indexOf() Case Insensitive

Last Updated : 25 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the different methods to make Array.indexOf() case insensitive in JavaScript

1. Using JavaScript toLowerCase() Method

Transform the search string and elements of the array to the lowercase using the .toLowerCase() method, then perform the simple search.

JavaScript
let a = ["GFG_1", "geeks", "GFG_2", "gfg"];
let el = "gfg_1";
let res = a.map((item) => 
	item.toLowerCase()).indexOf(el.toLowerCase());
console.log("The index of '" + el + "' is '" + res + "'.");

Output
The index of 'gfg_1' is '0'.

In this example

  • map(item => item.toLowerCase()): Converts all items in the array to lowercase for case-insensitive comparison.
  • indexOf(el.toLowerCase()): Converts el to lowercase and finds its index in the transformed array.

2. Using JavaScript toUpperCase() Method

Transform the search string and elements of the array to the upper case using the toUpperCase() method, then perform the simple search.

JavaScript
let a = ['GFG_1', 'geeks', 'GFG_2', 'gfg'];
let el = 'gfg_1';
let res = a.map(item => 
	item.toUpperCase()).indexOf(el.toUpperCase()) !== -1 ? 'present' : 'absent';
console.log("The index of '" + el + "' is '" + res + "'.");

Output
The index of 'gfg_1' is 'present'.

In this example

  • map(item => item.toUpperCase()): Converts all items in the array to uppercase for case-insensitive comparison.
  • indexOf(el.toUpperCase()): Converts el to uppercase and finds its index in the transformed array. If the item is found, it returns present, otherwise absent.

3. Using Array.findIndex() and RegExp

To make Array.findIndex() case insensitive in JavaScript using RegExp, create a regular expression with the `i` flag (ignores case).

JavaScript
const a = ["apple", "banana", "Orange", "pear"];
const term = "orange";

const ind = a.findIndex((item) => 
	new RegExp(term, "i").test(item));
console.log(ind);

Output
2

In this example

  • The code finds the index of ‘orange’ (case-insensitively) in the array a using a case-insensitive RegExp.
  • The index of the matching element (2 in this case).


Next Article

Similar Reads