JS: lastIndexOf() Method

In previous example, we saw how JavaScript treat string as an array and allow us to access its character using indexOf() method.

But sometimes, there are more than one occurrence of a character in the string. To know the index of last occurrence of a string. JavaScript has lastIndexOf() method in the string class.

Here is an example of the method – lastIndexOf().

<!DOCTYPE html>
<html>
<head>
   <title>JS: lastIndexOf() Method</title>
   <meta charset="utf-8">
</head>
<body>
<script>
   var animal = "elephant";
var out = animal.lastIndexOf('e');
console.log(out);
//outputs = 2
</script>
</body>
</html>

In the above example, there are two occurrence of character ‘e’. The lastIndexOf() method returns the index value of last occurrence of ‘e’ which is 2.

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag