String indexOf() Method with Example in JavaScript

JavaScript String indexOf() Method: Here, we are going to learn about the indexOf() method of String in JavaScript.
Submitted by IncludeHelp, on February 02, 2019

String indexOf() Method

indexOf() is method is a String method, it is used to check whether a substring exists in the given string or not. It returns the starting index of the substring from the string where substring exists. If substring does not exist in the string – it returns -1.

Syntax:

    String.indexOf(substring, [offset]);

Here, substring is the part of the string to be searched and [offset] is the specific index from where we want to search the substring, it's an optional parameter and it's default value is 0.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
<script>		
	var str = "IncludeHelp is for programmers";
	
	var substr = "is";		
	var index = str.indexOf(substr);
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");

	substr = "Hello";
	index = str.indexOf(substr);		
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");
	
	//searching from a specific index
	substr = "is";
	index = str.indexOf(substr,10);		
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");		

	substr = "is";
	index = str.indexOf(substr,20);		
	if(index!=-1)
		document.write(substr + " found at " + index + " position.<br>");
	else
		document.write(substr + " does not exist in the " + str + ".<br>");					
</script>
</body>
</html>

Output

is found at 12 position.
Hello does not exist in the IncludeHelp is for programmers.
is found at 12 position.
is does not exist in the IncludeHelp is for programmers.

JavaScript String Object Methods »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.