JavaScript String lastIndexOf() method

The lastIndexOf method in JavaScript is employed to locate the position of a specific character or substring within a series of character values. It functions in a manner akin to the indexOf method; however, the key distinction lies in the fact that it initiates its search from the end of the string rather than from the beginning.

The lastIndexOf function distinguishes between upper and lower case letters. The initial character in a string is indexed starting from zero. If a specified element cannot be found within the string, the method will return -1.

Syntax

The methods listed below are employed to determine the location of a specific element.

Method Description
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 denotes the individual character to be searched, such as 'a'.

index - It denotes the position of the index from which the search initiates.

str - This denotes the string that is to be searched, such as "Java".

JavaScript String lastIndexOf method example

Let us explore the different methods for locating the index of an element through the use of straightforward examples.

Example 1

In this section, we will display the location of an individual character.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.lastIndexOf('a'));

</script>

Output:

Example 2

In this illustration, we will specify the index position at which the search initiates.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.lastIndexOf('a',22));

</script>

Output:

Example 3

In this section, we will display the index of the initial character within a string.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.lastIndexOf("Java"));

</script>

Output:

Example 4

In this instance, we will specify the index position at which the search will commence.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.lastIndexOf("Java",19));

</script>

Output:

Example 5

In this section, we will attempt to locate the element by altering its case sensitivity.

Example

<script>

var web="Learn JavaScript on Example";

document.write(web.lastIndexOf("java"));

</script>

Output:

Input Required

This code uses input(). Please provide values below: