JavaScript lastIndexOf

The JavaScript lastIndexOf method is useful to return the index position of the last occurrence of a specified string. It will return -1 if the specified string is not found. The syntax of the JavaScript lastIndexOf function is

String_Object.LastIndexOf(Substring, Starting_Position)
  • Substring: String you want to search for.
  • Starting_Position (Optional): If you want to specify the starting point (starting index position), please determine the index value here.

If we specify the Negative number as Starting_Position, the LastIndexOf will start looking from Zero. When we specify the Out of range Index as Starting_Position, LastIndexOf will start looking from the Highest index number.

JavaScript lastIndexOf Example

The following set of examples will help you understand the JavaScript lastIndexOf Function.

In this example, Within the Script tag, we first declared two String variables, Str1 and Str2, and assigned corresponding values.

The first statement will find the Last index position of a substring “Script” and store the index value in Str3. You should count the space as One Character.

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

In the next line, we are looking for “abc” inside the Str2. Although the term abc repeats multiple times, the JavaScript LastIndexof function is writing the index position of the Last occurrence.

For Str6, let us change the starting position from default to 19. This statement will return the last occurrence of string abc starting at index position 19.

We used the document write statements to place the output content in the respective browser.

<!DOCTYPE html>
<html>
<head>
    <title> JavaScriptLastIndexOf </title>
</head>
<body>
    <h1> JavaScriptLastIndexOf </h1>
<script>
 var Str1 = "Learn JavaScript at Tutorial Gateway.org";
 var Str2 = "We are abc working at abc company";
 var Str3 = Str1.lastIndexOf("Script");
 var Str4 = Str1.lastIndexOf("abc"); // Non existing item
 var Str5 = Str2.lastIndexOf("abc");
 var Str6 = Str2.lastIndexOf("abc", 19);
 
 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 abc is:</b> " + Str6);
</script>
</body>
</html>
JavaScript LastIndexOf