String lastIndexOf() Method - Javascript String

Javascript examples for String:lastIndexOf

Description

The lastIndexOf() method returns the position of the last occurrence of a value in a string.

The string is searched from the end to the beginning.

Syntax

string.lastIndexOf(item, start);

Parameter Values

Parameter Description
searchvalue Required. The string to search for
start Optional. The position where to start searching backwards. If omitted, the default value is the length of the string

Return Value:

A Number, representing the position where the specified searchvalue occurs for the last time, or -1 if it never occurs

The following code shows how to Search a string for the last occurrence of "this":

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {//from  ww  w .j  a  v a2 s  .c  om
    var str = "this is a test this this a test.";
    var n = str.lastIndexOf("this", 20);
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

Related Tutorials