indexOf() method is used to search for the index of an element in a given array; it can also be used to find the position of a character or a substring in a string. The indexOf() method returns the position of the element/substring if it is found; else, it returns -1. The indexing starts from 0, so the first element of an array and the first word in a string always return 0.
How to use the indexOf() method
In this guide, we will learn how to use the indexOf() method to find the index of an element/substring in an array/string; but first, let’s discuss its syntax:
The indexOf() method takes two parameters:
- element/searchvalue: The first parameter is required. It can be an element of an array or a substring of which the index is required.
- starting_point: This parameter is optional. It tells the method to start the search from the specified point. It is 0 by default.
Now will use the indexOf() method to find the index of an element in an array as an example:
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).
Similarly, we can also use this method on a string:
It can also be used to find a single character:
The indexOf() method by default starts searching from 0; but we can pass the starting point as an argument as well:
The method has returned -1 as it cannot find ‘Rhino’ if it starts the search from 3. Now, if we change the starting point to 2, then:
Similarly for strings:
The index() method starts searching from 0 to the end of an array/string; and returns the index of the first occurrence of the search value. If there are two similar items in an array or a string and you want to find the index of the last one, then you should use the lastIndexOf() method:
Similarly for an array:
The indexOf() method is case-sensitive.
While programming, when working with arrays or strings, we often need to find the index of a specific element or a substring. The indexOf() method comes in handy in such situations.
In this how-to guide, we have learned how to use the indexOf() method to find the index of an item in a string/array. Moreover, we also discussed the type and parameters we can pass to the indexOf() method.