String lastIndexOf() method in JavaScript

You can use lastIndexOf() method in JavaScript to find index i.e position of the last appearance for the specified string. If the specified string is not found in the main string then it returns -1.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>lastIndexOf</title>
  <script>
    var str = "Try to find me here. If you failed find me at other places.";
    var index1 = str.lastIndexOf("find");
    document.write('position of find is:', index1);
    document.write("<br />");
    var index2 = str.lastIndexOf("search");
    document.write('position of search is:', index2);
  </script>
</head>
<body> 
</body>
</html>

Output:

position of find is:35
position of search is:-1

**Note:

lastIndexOf() methods returns -1 if specified string is not found.

Second parameter for lastIndexOf() method:

lastIndexOf() method in JavaScript can take the second parameter by which you can give a starting position for the search.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>lastIndexOf()</title>
  <script>
    var str = "Try to find me here. If you failed find me at other places.";
    var index = str.lastIndexOf("find", 20);
    document.write('position of find by using lastIndexOf is: ', index);
  </script>
</head>
<body>
</body>
</html>

Output:

position of find by using lastIndexOf is: 7

One Comment

Leave a Reply