JavaScript String lastIndexOf() method

The JavaScript string lastIndexOf() method is used to search the position of a particular character or string in a sequence of given char values. It behaves similar to indexOf() method with a difference that it start searching an element from the last position of the string.

The lastIndexOf() method is case-sensitive. The index position of first character in a string is always starts with zero. If an element is not present in a string, it returns -1.

Syntax

These are the following ways used to search the position of an element.

MethodDescription
lastIndexOf(ch)It returns the last index position of char value passed with method.
lastIndexOf(ch,index)It starts searching the element from the provided index value in the inverse order and then returns the index position of specified char value.
lastIndexOf(str)It returns the index position of first character of string passed with method.
lastIndexOf(str,index)It starts searching the element from the provided index value and then returns the index position of first character of string.

Parameters

ch - It represent the single character to search like 'a'.

index - It represent the index position from where search starts.

str - It represent the string to search like "Java".

JavaScript String lastIndexOf() method example

Let's see the various ways of searching the position of an element with help of simple examples.

Example 1

Here, we will print the position of a single character.

Test it Now

Output:

23

Example 2

In this example, we will provide the index value from where the search starts.

Test it Now

Output:

21

Example 3

Here, we will print the position of a first character of string.

Test it Now

Output:

20

Example 4

In this example, we will provide the index value from where the search starts.

Test it Now

Output:

6

Example 5

Here, we will try to search the element by changing its case-sensitivity.

Test it Now

Output:

-1





Latest Courses