JavaScript IndexOf

The JavaScript indexof method returns the index position of the first occurrence of a specified string. If the specified string not located, the indexof function will return -1. The syntax of the JavaScript indexof function is

String_Object.indexof(Substring, Starting_Position)
  • Substring: String you want to search inside the string_Object.
  • Starting_Position (optional): If you want to specify the starting point (starting index position), then please specify the index value here.

If the Starting_Position is a Negative number, JavaScript indexof starts looking from Zero. If the Starting_Position is Out of range Index, js IndexOf string function start looking from the highest index number.

JavaScript indexof Example

This example will help you understand the js indexof string Function.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScript IndexOf </title>
</head>
<body>
    <h1> JavaScript IndexOf </h1>
<script>
 var Str1 = "Learn JavaScript at Tutorial Gateway.org";
 var Str2 = "We are abc working at abc company";
 var Str3 = Str1.indexOf("Script");
 var Str4 = Str1.indexOf("abc"); // Non existing item
 var Str5 = Str2.indexOf("abc");
 var Str6 = Str1.indexOf("Script", 5);
 var Str7 = Str2.indexOf("abc", 10);
 
 document.write("<b> Index position of Script is:</b> " + Str3);
 document.write("<br \> <b> Index position of abc is:</b> " + Str4);
 document.write("<br \> <b> Index position of abc is:</b> " + Str5);
 document.write("<br \> <b> Index position of Script is:</b> " + Str6);
 document.write("<br \> <b> Index position of abc is:</b> " + Str7);
</script>
</body>
</html>

TIP: The index position in JavaScript indexof Function will start from 0, Not 1.

JavaScript IndexOf

It finds the index position of a substring ‘Script’ and stores the index value in Str3.

var Str3 = Str1.indexOf("Script");

In the next line, we are looking for a non-existing “abc” inside the Str1. Since JS indexof string function doesn’t find the substring, it is returning -1 as output

 var Str4 = Str1.indexOf("abc"); // Non existing item

Here, we are looking for “abc” inside the Str2 using js IndexOf function.

var Str5 = Str2.indexOf("abc");

From the above, though abc reappeared multiple times, the Javascript indexof string function written the index position of a first occurrence. Now, let us modify the starting position from default 0 to 10. It means the below js indexof string code returns the first occurrence of string abc starting at index position 10.

 var Str7 = Str2.indexOf("abc", 10);