Javascript - String lastIndexOf() Method

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

Description

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

The string is searched from the end to the beginning, but returns the index starting from the beginning at position 0.

It returns -1 if the value to search for never occurs.

The lastIndexOf() method is case sensitive!

Syntax

string.lastIndexOf(searchvalue,start)

Parameter Values

Parameter Require Description
searchvalue Required. The string to search for
start Optional. The position where to start the search. If omitted, the default value is the length of the string

Return

A Number, representing the position where the specified searchvalue occurs for the last time, or -1 if it never occurs

Example

Search a string for the last occurrence of "planet":

Demo

//locate the last occurance of a specified value.
var str = "Hello planet earth, this is a test planet.";
var n = str.lastIndexOf("planet");
console.log(n);/* ww w .  ja  v  a 2 s  . c  o m*/

//Search a string for the last occurrence of "planet", starting the search at position 20:
//locate the last occurance of a specified value, starting the search at position 20.
str = "Hello planet earth, this is a test planet.";
n = str.lastIndexOf("planet", 20);
console.log(n);

Result