lastIndexOf() String Method in JavaScript Explained
Whenever you use lastIndexOf() on a string, the method does the following:
- It searches its calling string for the method's first argument.
- It returns the index position of the last match, or
-1
if the method found no match.
- A calling string is a string on which you used
lastIndexOf()
. So, in"Hello, world!".lastIndexOf("world")
,"Hello, world!"
is the calling string. lastIndexOf()
is sometimes written asString.prototype.lastIndexOf()
because it is a method of theString
object'sprototype
property.
Syntax of the lastIndexOf()
Method
lastIndexOf()
accepts two arguments. Here is the syntax:
callingString.lastIndexOf(valueToFind, startIndex);
Argument 1: valueToFind
A valueToFind
is the first argument accepted by the lastIndexOf()
method. It defines the value you wish to find in the calling string.
Example 1: Find the index of the last Tuesday
"Sunday, Tuesday, Friday, Sunday, Tuesday, Friday".lastIndexOf("Tuesday");
// The invocation above will return: 33
Example 2: Find the index of the last Friday
"Sunday, Tuesday, Friday, Sunday, Tuesday, Friday".lastIndexOf("Friday");
// The invocation above will return: 42
Example 3: Find the index of the last 7
"1, 3, 5, 7, 9, 1, 3, 5, 7, 9".lastIndexOf(7);
// The invocation above will return: 24
Argument 2: startIndex
The startIndex
argument is optional. It specifies the index position where you want the computer to start searching for the valueToFind
argument.
Keep in mind that lastIndexOf()
, by default, searches backward from a startIndex
of +Infinity
.
Therefore, if you omit the startIndex
argument, the computer will search the entire string backward (right to left).
Example 1: Find the index of the last Tuesday
from the 54th index position
let daysOfTheWeek =
"Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Tuesday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday";
daysOfTheWeek.lastIndexOf("Tuesday", 54);
// The invocation above will return: 16
The snippet above returned 16
because the search started backward from the fifty-fourth index position.
However, suppose you omit the startIndex
argument, the computer will search backward from the last item in the calling string (callingString.length - 1
).
Here's an example:
let daysOfTheWeek =
"Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Tuesday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday";
daysOfTheWeek.lastIndexOf("Tuesday");
// The invocation above will return: 89