The lastIndexOf() method of the String class in JavaScript returns the index within the calling String object of the last occurrence of the specified value, searchString, starting the search at fromIndex. Returns -1 if the value is not found.
There are 2 variations for the syntax of String.lastIndexOf() method. They are:
lastIndexOf(searchString)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The string to search for within this string. |
This method returns the index within the calling String object of the last occurrence of searchString.
Returns value of type Number
.
lastIndexOf(searchString, fromIndex)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchString | required | The string to search for within this string. |
fromIndex | optional | The position in the calling string to start the search backward from. Defaults to the length of the string. |
This method returns the index within the calling String object of the last occurrence of searchString, starting the search backward at fromIndex.
Returns value of type Number
.
In JavaScript, we can use the lastIndexOf()
method to find the last occurrence of a specified substring.
For example,
str
with the value 'Hello, world!'
.lastIndexOf()
method with the argument 'o'
to find the last occurrence of the character 'o'
.index
.index
to the console using the console.log()
method.const str = 'Hello, world!';
const index = str.lastIndexOf('o');
console.log(index);
8
In JavaScript, we can use the lastIndexOf()
method to find the last occurrence of a specified substring, starting the search backward from a given position.
For example,
str
with the value 'Hello, world! Hello!'
.lastIndexOf()
method with the arguments 'Hello'
and 15
to find the last occurrence of the substring 'Hello'
, starting the search backward from position 15
.index
.index
to the console using the console.log()
method.const str = 'Hello, world! Hello!';
const index = str.lastIndexOf('Hello', 15);
console.log(index);
0
In JavaScript, we can use the lastIndexOf()
method to search for a substring that does not exist in the string.
For example,
str
with the value 'Hello, world!'
.lastIndexOf()
method with the argument 'JavaScript'
to search for the substring 'JavaScript'
within the string.index
.index
to the console using the console.log()
method.const str = 'Hello, world!';
const index = str.lastIndexOf('JavaScript');
console.log(index);
-1
In this JavaScript tutorial, we learned about lastIndexOf() method of String: the syntax and few working examples with output and detailed explanation for each example.