Return to Kroll Design home page

JavaScript Tutorials

 
« Return

lastIndexOf() method for strings

The lastIndexOf method searches the specified string for the specified substring, starting at the end of the string and working backwards, and returns the location of the substring, if found. If the substring is not found, lastIndexOf returns a -1. Compare with the indexOf method.

There are two forms of this method. In one form, you add an optional 3rd parameter to specify where to start searching for the substring. This allows you to bypass any ending section of the string that you don't want to search.

Code:

<script type="text/javascript">
//<![CDATA[

function lastIndexOfFunc(mainString, searchString, startSearchAt)
{
    if (startSearchAt === undefined)
      {
      searchStringLocation = mainString.lastIndexOf(searchString);
      document.write("Final location of \"", searchString, "\" within \"", mainString, "\" : ", searchStringLocation, "<br>");
      }
    else
      {
      searchStringLocation = mainString.lastIndexOf(searchString, startSearchAt);
      document.write("Final location of \"", searchString, "\" within \"", mainString, "\", skipping the final ", startSearchAt, " characters: ", searchStringLocation, "<br>");
      }
}

lastIndexOfFunc("This is how to do it.", "is");
document.write("<br>");

lastIndexOfFunc("zzz", "z");
document.write("<br>");

lastIndexOfFunc("misterdavid@david.com", "david", 10);  // skip the final 10 characters when searching
document.write("<br>");

lastIndexOfFunc("misterdavid@david.com", "dave");  // -1 means "not found"

//]]>
</script>

Output:



 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM