Open In App

Which method returns the index within calling String object of first occurrence of specified value ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will know how to return the index of the first occurrence of the specified value(can be a string or character) in the string, also will understand their implementation through the examples. 

JavaScript indexOf() Method: The indexOf() method is a built-in & case-sensitive method that returns the index of the first occurrence of the specified value in the calling string object. It will return -1 if no such value is found.

The main usage of this method is to find the existence of the particular string or character in the string because the method returns -1 if the provided search value is not present. This method can also be used to calculate the frequency of specific search value in the string.

Syntax:

indexOf(searchValue, index)

Example 1: This example illustrates the search value that can be a string or any character.

Javascript




let myString = "Hello, GeeksforGeeks Learner!";
console.log("The index of 'Hello' in string is: ",
myString.indexOf("Hello"));
console.log("The index of first occurrence of 'G' is: ",
myString.indexOf('G'));


Output:

The index of 'Hello' in string is:  0
The index of first occurrence of 'G' is:  7

Explanation: In the first line, we have declared a string with initialization, and later we are calling the indexOf() method with this string as a calling object by providing the “Hello” as an argument. Now, this method will return the first occurrence of “Hello” in the string which is 0. After then, we have searched for the character ‘G’ in the string. Here, this method will return 7 because that is the first occurrence.

Example 2: This example describes finding the first occurrence of the argument character or string wrt to the specific position.

HTML




let myString = "Hi Javascript Developer";
console.log("The index of first occurrence 'i' from 3rd index is: ",
             myString.indexOf("i", 3));
console.log("The index of first occurrence 'Hi' from the 7th index is: ",
             myString.indexOf('Hi', 7));


Output:

The index of first occurrence 'i' from 3rd index is:  10
The index of first occurrence 'Hi' from the 7th index is:  -1

Explanation:  Here, we are calling the indexOf() method by providing the start index of searching explicitly, In the first one, we are calling the method by providing ‘i’ and 3. The ‘i’ will be found on the 10th index if the starting search index is 3. Similarly in the second one, we have provided the ‘Hi’ for searching from the 7th index but there is no occurrence of “Hi” after the 7th index hence -1 will be returned.


Last Updated : 09 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads