The Wayback Machine - https://web.archive.org/web/20240926112209/https://www.geeksforgeeks.org/javascript-string-lastindexof-method/
Open In App

JavaScript String lastIndexOf() Method

Last Updated : 16 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Syntax:

str.lastIndexOf(searchValue , index)

Parameters:

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

  • 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

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

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: 

  • Google Chrome 3
  • Microsoft Edge 12
  • Mozilla Firefox 3.0
  • Safari 5
  • Opera 10.5

JavaScript String lastIndexOf() Method – FAQs

What does lastIndexOf() do In JavaScript?

lastIndexOf() searches a string for a specified substring and returns the index of its last occurrence, or -1 if not found.

How do you use lastIndexOf() to find a substring?

Use str.lastIndexOf(searchValue) to find the last occurrence of searchValue in str, starting from the end of the string.

Is lastIndexOf() case-sensitive?

Yes, lastIndexOf() is case-sensitive. To perform a case-insensitive search, use methods like toLowerCase() on both str and searchValue.

Can lastIndexOf() search from a specific position?

Yes, str.lastIndexOf(searchValue, fromIndex) starts searching from fromIndex backwards. If omitted, it searches the entire string.

What does lastIndexOf() return if the substring is empty?

If searchValue is an empty string (“”), lastIndexOf() returns the position of the last character in str plus one.

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.


Previous Article
Next Article

Similar Reads

TypeScript | String lastIndexOf() Method
The lastIndexOf() is an inbuilt function in TypeScript which is used to get the index within the calling String object of the last occurrence of the specified value. Syntax: string.lastIndexOf(searchValue[, fromIndex]) Parameter: This method accepts two parameter as mentioned above and described below: searchValue: This parameter is a string repres
1 min read
JavaScript typedArray.lastIndexOf() Method
The typedArray.lastIndexOf() is an inbuilt function in JavaScript which is used to return the last index of the typedArray at which a given element is present otherwise it returns -1 if the element is not present. Syntax: typedArray.lastIndexOf(search_Element, from_Index]) Parameters: It accepts two parameters which are specified below: search_Elem
2 min read
JavaScript Array lastIndexOf() Method
The JavaScript Array lastIndexOf() Method is used to find the index of the last occurrence of the search element provided as the argument to the function. Syntax: array.lastIndexOf(element, start)Parameters: This method accepts two parameters as mentioned above and described below: element: This parameter holds the element whose index will be retur
3 min read
Node.js Buffer.lastIndexOf() Method
Buffer is a temporary memory storage that stores the data when it is being moved from one place to another. It is like an array of integers. The Buffer.lastIndexOf() Method checks for a given value in the buffer and returns its index where it is present. If the same value is present more than once, then it returns the last index where the value is
2 min read
Ember.js ArrayProxy lastIndexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Ember.js MutableArray lastIndexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
Ember.js EmberArray lastIndexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
3 min read
Ember.js Ember.NativeArray lastIndexOf() Method
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which is based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity. Currently, it is utilized by a large number of webs
4 min read
TypeScript Array lastIndexOf() Method
The Array.prototype.lastIndexOf() method in TypeScript is used to find the last index at which a given element can be found in the array, searching backwards from the fromIndex. It returns the index of the found element, or -1 if the element is not present. Syntax: array.lastIndexOf(searchElement[, fromIndex])Parameter: This method accepts two para
2 min read
Lodash _.lastIndexOf() Method
Lodash _.lastIndexOf() method is like the _.indexOf method except that it iterates over elements of an array from right to left. Syntax:_.lastIndexOf(array, value, [fromIndex=array.length-1]);Note: If the value is not found in the array -1 is returned. Parameters: array: It is the array in which value is to be found.value: It is the value to be loo
3 min read
Underscore.js _.lastindexOf() Function
_.lastIndexOf() function: It finds the index of an element in an array. If the element is repeated then it gives the index of that element which is closest to the end. It is used when we have a number of repeated elements in the array and we want to find the index of that repeated element which is nearest to the end. Syntax:_.lastIndexOf(array, val
3 min read
Javascript Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Javascript Program to Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
4 min read
JavaScript Program to Return Original String of Compressed String
The compressed string follows a format where each character is followed by its count. we need to print a string having the same number of characters present in the compressed string. Below are the approaches to return original string of compressed string using Example: Input: compressedString= "a3b2c1"Output: originalString="aaabbc"These are the fo
2 min read
Smallest Window in a String Containing all the Characters of Another String using JavaScript
Given two strings, "str" (the larger string) and "pattern" (the smaller string), the task is to find the smallest window in "str" that contains all the characters of "pattern" in any order using JavaScript. Examples: Input: str = "ADOBECODEBANC"pattern = "ABC"Output: BANCInput: str = "this is a test string"pattern = "tist";Output: t striTable of Co
3 min read
JavaScript Insert a string at position X of another string
Given two strings, the task is to insert one string in another at a specified position using JavaScript. We're going to discuss a few methods, these are: Methods to Insert String at a Certain IndexTable of Content Method 1: Using JavaScript String slice() and Array join() MethodsMethod 2: JavaScript String substr() Method Method 3: Using JavaScript
4 min read
How to check a given string is an anagram of another string in JavaScript ?
In this article, we will learn how to check a given string is an anagram of another string in JavaScript. Before that, we should learn what is an anagram. An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different term or phrase. Some of the examples are given below
3 min read
How to check if a string "StartsWith" another string in JavaScript ?
In JavaScript, the 'startsWith()' method is a built-in method that allows one to check whether a string starts with a specified substring. Syntax: It takes a single argument, which is the substring we want to check whether the string starts with. string.startsWith(searchString[, position])Approach 1: Using startWith methodThe 'searchString' paramet
2 min read
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string. Example: Input: "101010"Output: True, binary stringInput: "110211"Output: Falee,Explanati
4 min read
Difference between String.slice and String.substring in JavaScript
These 2 functions are quite similar in their Syntax But are different in some cases. Let's see the difference between them. JavaScript slice() Method:This method selects the part of a string and returns the selected part as a new string. Start and end parameters are used to specify the extracted part. The first character starts with index 0. Syntax
3 min read
Difference Between String.prototype.replace() and String.prototype.replaceAll() in JavaScript
The String.prototype.replace and String.prototype.replaceAll are frequently used to the modify strings. Understanding the differences between these methods is crucial for the effective string handling. This article explores the characteristics, applications and examples of both the replace and replaceAll methods. These are the following topics that
3 min read
How to count string occurrence in string using JavaScript ?
In JavaScript, we can count the string occurrence in a string by counting the number of times the string is present in the string. This can be done in the following ways: Table of Content Approach 1: Using match() functionApproach 2: Using a loopApproach 3: Using split() functionApproach 4: Using Indexof()Approach 5: Using regular expressionsApproa
4 min read
Check if a String is Valid JSON String using JavaScript
In JavaScript, JSON (JavaScript Object Notation) is a format used for representing structured data as text. It's widely used for data exchange between web servers and browsers. Sometimes, we need to check if a given string is a valid JSON before using it in our code. If the string follows the correct JSON format, we return true, otherwise, we retur
5 min read
Javascript Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string in two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview 1- There can be only two cases: a) Clockwi
2 min read
TypeScript String String.fromCodePoint() Method
The fromCodePoint() is an inbuilt TypeScript String method. It is mainly used to get the string value of any given Unicode point value. This method is really helpful when you want to handle characters that are not readily available through keyboard input. Syntax:String.fromCodePoint(...codePoints: number[]): stringParameters:...codePoints: An array
1 min read
String includes() Method in JavaScript
JavaScript str.includes() function is used to check if the argument string is present in the given string or not. This function is case-sensitive. The syntax of this function is as follows: str.includes(searchString, position) Arguments The first argument to this function searchString is the string to be searched in the given string. The second arg
2 min read
How to define a new method for calculating the actual length of string in JavaScript using prototype ?
In JavaScript, you can use the String. length property to get the length of a string variable. This method will give you a string that is enclosed in quotes no matter what it is. We will get one issue while using this String. length method. Let's discuss when we will get the issue with that String.length method and how to solve it. Syntax: string.l
3 min read
JavaScript method to get the URL without query string
The task is to get the URL name of the page without using a query string with the help of JavaScript. replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value. Syntax: string.replace(searchVal, newvalue) Parameters: searchVal: This parameter is required. I
3 min read
JavaScript String trimEnd() and trimRight() Method
This article demonstrates trimEnd and trimRight methods of JavaScript string. Both methods are used to perform the same task and their implementation is shown below: JavaScript trimEnd() methodThe trimEnd() method in JavaScript is used to remove white space from the end of a string. The value of the string is not modified in any manner, including a
2 min read
JavaScript String trimStart() and trimLeft() Method
This article demonstrates trimEnd and trimRight methods of JavaScript string. Both methods are used to perform the same task and their implementation is shown below: JavaScript trimStart() method:The trimStart() method in JavaScript is used to remove whitespace from the beginning of a string. The value of the string is not modified in any manner, i
2 min read