For a clearer understanding, let’s understand the syntax:
- The “ARRAY” refers to the JS array to which indexOf is being applied.
- The “SearchValue” presents the value being searched in the array.
- Lastly, the “FromIndexNo” is an optional parameter that denotes the index number from which the search will begin. The search will automatically start from the 0th index if it is not added.
As discussed, there are two main components of the “indexOf” method, i.e., the first is the array on which this function is to be applied, and the second is the “value” to be searched. The third parameter is used as per the scenario’s requirement.
Example 1: Find Index Number of a Substring
The following code gets the index number of a substring in a string:
The above code’s description is as follows:
- A string is initialized.
- The “indexOf” method searches for the substring “Script,” and the method will start searching from the 0th index as we have not defined the index parameter.
The “Script” is present at the 4th index from the start (only considers the first occurrence of the searched value).
Define the Start Index.
Let’s define the index from which the search should begin. The same example code (as in Example 1) is modified, and now the “indexOf” will search for the index of the “Script” starting from the index number 20:
Now, when you look at the output, it shows the index of the “Script” keyword that occurs after index 20, i.e., 59.
Example 2: Find Index of an Element in an Array
In this example, an array of numbers is initialized, which will be passed through the “indexOf” method to get the index of the specific element of the array:
var arr =[1, 13, 5, 17, 25, 19, 3, 17, 51]; var res = arr.indexOf(17); console.log(res);
An array is initialized above and the index of the element “17” will be traced.
The output is “3,” which is the index of the element “17” as its first occurrence.
What if the Element Being Searched is Not Present in Array/String?
You might be thinking about how the “indexOf” behaves if the item/element being searched is unavailable. In such a case, the compiler will not throw an error/exception; it will give an output “-1,” which can be seen in the following snippet where the number “117” was being searched, which does not exist in the “arr”: