Skip to content

JavaScript lastIndexOf() | String method

  • by

JavaScript lastIndexOf() string method is used to get the last occurrence of a substring in a string. It searches the position of a particular character or string in a sequence of given char values.

lastIndexOf(searchString)
lastIndexOf(searchString, position)

This method returns the index (position) of the last occurrence of a specified value in a string. And returns -1 if the value is not found.

Note: This method is case-sensitive.

JavaScript lastIndexOf()

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let text = "Mr. Green has a green Mouse";
    
    let res = text.lastIndexOf("green");
    console.log(res)

    // case sensitive
    let out = text.lastIndexOf("Green");
    console.log(out)

  </script>

</body>
</html>

Output:

JavaScript lastIndexOf String method

If you pass the fromIndex the argument to the string, the lastIndexOf() method will start searching backward from the fromIndex as shown in the following example:

let str = 'JavaScript';
let index = str.lastIndexOf('a',2);

console.log(index);//1

When Substring Is Not Found

var str = "I love JavaScript";

// passing a substring that is not in a given string
var result = str.lastIndexOf("Python")


console.log(result); //-1

Finding the last occurrence of a substring in a log file:

let logData = "Error: Disk full. Error: Network down. Error: Disk full.";
let lastErrorIndex = logData.lastIndexOf("Error");
console.log(lastErrorIndex); // 28

Checking for the last occurrence of a specific number in an array:

let numbers = [1, 3, 7, 3, 9, 3];
let lastThreeIndex = numbers.lastIndexOf(3);
console.log(lastThreeIndex); // 5

By using lastIndexOf(), you can efficiently find the position of elements from the end of your data structures, which can be particularly useful in various algorithms and data processing tasks.

These are the following ways used to search for the position of an element.

MethodDescription
lastIndexOf(ch)It returns the last index position of the char value passed with the method.
lastIndexOf(ch,index)It starts searching the element from the provided index value in the inverse order and then returns the index position of the specified char value.
lastIndexOf(str)It returns the index position of the first character of the string passed with the method.
lastIndexOf(str,index)It starts searching the element from the provided index value and then returns the index position of the first character of a string.

Do comment if you have any doubts or suggestions on this JS string method tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading