DEV Community

Cover image for String.prototype.indexOf() vs String.prototype.lastIndexOf()
Mura0083
Mura0083

Posted on

String.prototype.indexOf() vs String.prototype.lastIndexOf()

"indexOf()" Description:

The indexOf() method is used to return the index of a value/parameter's first appearance, from within a called string.

Syntax:

  1. indexOf(value)
  2. indexOf(value, fromIndex)

"Value" and "fromIndex":

The value is the string whose index we're looking for, from within the original string variable. For example:
Screenshot example1
This method looks for the value starting from left to right to find the first occurrence of the value.

If value is not in the original string, such as "b", the output will come as -1.

The fromIndex is an optional parameter(value from 0 to string.length) that lets you choose the index where the search starts from. If fromIndex is not specified, the search automatically starts from index 0.

Output:

Output is the index of the value in the original string, so it can be any number from 0 to string.length - 1.

If the value is a string with multiple letters or numbers, the output/index will be positioned where the value starts, from the left. For example:
Screenshot example2
The string "great" is going to have the output of "10" because the "g" stands at that index and that's where the string starts.

"lastIndexOf()" Description:

The lastIndexOf() is a method that returns the index of a specified value's last appearance in the original string.

Syntax:

  1. lastIndexOf(value)
  2. lastIndexOf(value, fromIndex)

Note: Value and fromIndex stay the same as for "indexOf"

Output:

This time, the method is looking for the last time our value appears in the string, then output the index. For example:
Screenshot example3
Therefore, the output shall be 22 because that is the index for the last "a" in the original string.

Top comments (0)