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

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
PERSONIL BTS
PERSONIL BTS
1 year ago

It’s an amazing paragraph in favor of all the web viewers; they will get benefit from it I am sure.

katte orm
katte orm
1 year ago

Nice post. I learn something new and challenging on sites I stumbleupon everyday.
It’s always useful to read through content from other writers and use something
from their sites.