String Method: lastIndexOf

Another way to find a string in a string, is by using the lastIndexOf() method, which returns the index of (or location of) the last occurrence of a specified text in a string. In this example, we are looking for the last occurence of the text string locate:

HTML file: Displayed by browser:
<body>
<p id="p1">"Please locate where 'locate' occurs!."</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var str = document.getElementById("p1").innerHTML;
    var pos = str.lastIndexOf("locate");
    document.getElementById("demo").innerHTML = pos;
}
</script>
</body>

"Please locate where 'locate' occurs!."

If there was no such text string, then this function would have returned a value of -1. Although this function looks for the text string from the end, the numbering of character positions within the string always starts from the beginning. The first character of the string has position 0, the second has position 1, the third has position 2, and so forth...

A second parameter is acceptable as the starting position for the search.

BackTable of ContentsNext