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>
    <title> JavaScriptLastIndexOf </title>
    <h1> JavaScriptLastIndexOf </h1>
 var Str1 = "Learn JavaScript at Tutorial";
 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);
JavaScript LastIndexOf

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.