javascript
  1. javascript-lastindexof

JavaScript lastIndexOf()

The lastIndexOf() method in JavaScript returns the last index of a specified search value within an array or string. This method compares the specified search value with elements in the array or string from right to left.

Syntax

The syntax of the lastIndexOf() method is as follows:

array.lastIndexOf(searchValue[, fromIndex])
string.lastIndexOf(searchValue[, fromIndex])
  • searchValue: The value to search for in the array or string.
  • fromIndex (Optional): The index to start searching from. By default, the search starts from the last index of the array or string.

Example

The following example demonstrates the usage of the lastIndexOf() method:

const arr = [10, 20, 30, 40, 50];
const index = arr.lastIndexOf(30);
console.log(index); // Output: 2

const str = "Hello, World!";
const index = str.lastIndexOf("l");
console.log(index); // Output: 10

Output

The output of the above example will be:

2
10

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LastIndexOf Example</title>
</head>
<body>

<script>
    // Array example
    const arr = [10, 20, 30, 40, 50];

    // Get the last index of 30 in the array
    const arrIndex = arr.lastIndexOf(30);
    
    // Log the result
    document.write("<p>Last index of 30 in the array: " + arrIndex + "</p>");

    // String example
    const str = "Hello, World!";

    // Get the last index of 'l' in the string
    const strIndex = str.lastIndexOf("l");

    // Log the result
    document.write("<p>Last index of 'l' in the string: " + strIndex + "</p>");
</script>

</body>
</html>

Try Playground

Explanation

In the above example, we have an array of numbers and a string. We use the lastIndexOf() method to find the last index of 30 in the array arr and the last index of l in the string str.

Use

The lastIndexOf() method is useful in scenarios where you want to find the last occurrence of a specific element in an array or string.

Important Points

  • The lastIndexOf() method returns -1 if the specified search value is not found in the array or string.
  • For strings, the lastIndexOf() method is case sensitive.
  • If the fromIndex argument is greater than or equal to the array or string length, the entire array or string will be searched.
  • If the fromIndex argument is negative, the search starts from the end of the array or string minus the absolute value of the fromIndex.

Summary

The lastIndexOf() method is a useful method in JavaScript for finding the last index of a specified search value within an array or string. It can be used when you want to search an array or string from the right to left and need to find the last occurrence of a specific element.

Published on: