Learn how to check if elements or characters are present in Arrays or Strings with the indexOf method in javascript.
Arrays
indexOf method finds the index of the first matching element in the array and returns it. If element is not present then -1
is returned.
It searches the element with strict equality ===
.
const list = [1, 2, 3, 4, 5, 6, 7]; const index = list.indexOf(1); console.log(index); //0 const index = list.indexOf(11); //-1
The indexOf method takes two parameters as input.
Array.indexOf(element, startFrom)
element
- Required. Element whose index you are looking for.
startFrom
- Optional. Index from where the search of the element should start from.
- If
startFrom
is greater than Array’s length then-1
is returned.
Search element after the startFrom index
const list = [1, 2, 3, 4, 5, 6, 7]; const index = list.indexOf(4, 5); console.log(index); //-1
Search element before the startFrom index
const index = list.indexOf(5, 4); console.log(index); //4
Search element when startFrom index is greater than Array’s length
const index = list.indexOf(5, 9); console.log(index); //-1
String
We can only search for the position of characters with String’s indexOf method. It works same as the Array’s indexOf method.
const str = 'I am Prashant Yadav'; const index = str.indexOf('a'); console.log(index); //2
String.indexOf(characters, startFrom)
characters
- Required. Character whose position you want to find.
startFrom
- Optional. A numeric value from where you want the search to start from.
- If
startFrom
is less than0
then the search will start from0
and if it is greater than String’s length then the search will begin atString.length
.
You can search the index of white space as well.
const str = 'I am Prashant Yadav'; const index = str.indexOf(' '); console.log(index); //1
Search the index after the fourth character.
const str = 'I am Prashant Yadav'; const index = str.indexOf('a', 4); console.log(index); //7
Searching with the negative index
const str = 'I am Prashant Yadav'; const index = str.indexOf('a', -1); console.log(index); //2
Searching with the index greater than string’s length
const str = 'I am Prashant Yadav'; const index = str.indexOf('a', str.length+1); console.log(index); //-1