Open In App

JavaScript String lastIndexOf() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The lastIndexOf() method in JavaScript is used to search for the last occurrence of a specified substring within a string.

It returns the index of the last occurrence of the specified substring, or -1 if the substring is not found.

String lastIndexOf() Syntax

str.lastIndexOf(searchValue , index)

String lastIndexOf() Parameters

lastIndexOf() Method accepts 2 parameters which are discussed below:

Parameter

Description

searchvalue

The searchvalue is the string that is to be searched in the base string.

index

defines the starting index from where the searchvalue is to be searched in the base string backward

String lastIndexOf() Return value

This method returns the index of the string (0-based) where the searchvalue is found for the last time. If the searchvalue cannot be found in the string then the method returns -1

JavaScript String lastIndexOf() Method Examples

Example 1: Finding Last Occurrence of Substring in JavaScript

The function func() initializes a string variable str with the value ‘GeeksforGeeks’. It then uses the lastIndexOf() method to find the index of the last occurrence of the substring ‘for’ within the string str. The index, which is 5, is then printed to the console.

JavaScript




function func() {
    let str = 'GeeksforGeeks';
    let index = str.lastIndexOf('for');
    console.log(index);
}
func();


Output

5

Example 2: Case-sensitive Search with JavaScript’s lastIndexOf()

The func() function initializes a string variable str with the value ‘Departed Train’. It then uses the lastIndexOf() method to find the index of the last occurrence of the substring ‘train’ (case-sensitive) within the string str. Since ‘train’ is not found in ‘Departed Train’, -1 is printed to the console.

JavaScript




// JavaScript to illustrate lastIndexOf() method
 
function func() {
 
    // Original string
    let str = 'Departed Train';
 
    // Finding index of occurrence of 'train'
    let index = str.lastIndexOf('train');
    console.log(index);
}
func();


Output

-1

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browsers: 

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 6 and above
  • Opera 3 and above
  • Safari 1 and above

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads