Home >>JavaScript String Methods >JavaScript String lastIndexOf() Method

JavaScript String lastIndexOf() Method

JavaScript String lastIndexOf() Method

JavaScript lastIndexOf() method is used to return the position of the last occurrence of any specified value in a given input string. It is case sensitive. It searches the string from the end to the beginning but returns the index starting at the beginning at position 0. It returns -1 if the specified value never occurs.

Syntax:

string.lastIndexOf(searchvalue, start)

Parameter Values

Parameter Description
searchvalue This is a required parameter. It defines the string to search for.
start This is an optional parameter. It defines the position where to start the search. 

Browser Support

Method Chrome Edge Firefox Safari Opera
lastIndexOf() Yes Yes Yes Yes Yes

Here is an example of lastIndexOf() method:

<html>
<body>
<p>Click the button to see the Output</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = "Welcome to PHPTPOINT.";
  var n = str.lastIndexOf("PHP");
  document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>

Output:

Click the button to see the Output

 

Example 2:

<html>
<body>
<p>Click the button to see the Output</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
function myFunction1() {
  var str = "Welcome to PHPTPOINT.";
  var n = str.lastIndexOf("PHP",12);
  document.getElementById("demo1").innerHTML = n;
}
</script>
</body>
</html>
Output:

Click the button to see the Output

 


No Sidebar ads