Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




indexOf() - FUNCTION


indexOf() Function


The indexOf() Function is used to find the starting position of the substring.


Example :



<html>
<body>  
<script>

	var x = "Hello Beautiful World"
	var y = x.indexOf("Beautiful")
	document.write("The substring is located at the position ",y)
    
</script>      
</body>
</html>


Output :



  The substring is located at the position 6

In the above code, we have declared a String Hello Beautiful World and assigned it to a variable x.


var x = "Hello Beautiful World"
java_Collections


And we would be searching the substring Beautiful, from the String, Hello Beautiful World.


So, we have used the indexOf() Function to find the substring Beautiful.


var y = x.find("Beautiful")

And what indexOf() Function does is, goes to the String Hello Beautiful World and searches for the position of the substring Beautiful.

java_Collections

And finds the substring Beautiful in the 6th position. And the position (i.e. 6) is stored in variable y.

java_Collections

And thus prints the position.


document.write("The substring is located at the position ",y)

Output :



  The substring is located at the position 6

Now, let us say you have the below String,


"The Beautiful world is Beautiful indeed"

And you have to search for the second occurrence of Beautiful.


To solve this, you can add a second and a third parameter used by indexOf() function that tells the range, and in between the range the substring can be checked.


Let us see with the below example.


Example :



<html>
<body>  
<script>

	var x = "The Beautiful world is Beautiful indeed"
	var y = x.indexOf("Beautiful", 20, 35)
	document.write("The substring is located at the position ",y)
    
</script>      
</body>
</html>


Output :



  The substring is located at the position 23

So, if you see the above output, only the second occurrence of Beautiful is searched for.


That is because of the below line,


var y = x.indexOf("Beautiful", 20, 35)

Where we have specified the the range as 20 and 35, in second and third parameter.


Which says that search for the substring Beautiful in the positions between 20 to 35.


And thus we got the position as 23 assigned to the variable y,

java_Collections