JavaScript lastIndexOf()Method

String 对象参考手册JavaScript String Object

Example

Find the position of the last occurrence of the string "example":

var str="I am from example,welcome to example site."; var n=str.lastIndexOf("example");

nOutput:

28

Try it Yourself »

Definition and Usage

The lastIndexOf() method returns the position of the last occurrence of a specified string value. If the second parameter start is specified, it searches backward from the specified position in a string.

Note:This method retrieves the string from back to front, but the return value is calculated from the starting position (0) as the position of the last occurrence of the substring. It checks whether it contains the string.

The search begins at the start position in the string or at the end of the string (when start is not specified).

If no matching string is found, -1 is returned.

Note:The lastIndexOf() method is case-sensitive!

Tip:You can also refer to similar methodsindexOf() 。


Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

All major browsers support the lastIndexOf() method


Syntax

string.lastIndexOf(searchvalue,start)

Parameter Values

Parameter Description
searchvalue Required. Specifies the string value to be searched.
start Optional integer parameter. Specifies the position in the string to begin the search. Its valid values are 0 to stringObject.length - 1. If this parameter is omitted, the search will start from the last character of the string.

Return Value

Type Description
Number The position of the last occurrence of the searched string, or -1 if no matching string is found.

Technical Details

JavaScript Version: 1.0


More Examples

Example

Search for the last occurrence of the string "example" starting from the 20th character:

var str="I am from example,welcome to example site."; var n=str.lastIndexOf("example", 20);

nOutput:

10

Try it Yourself »

Example

Search backward for the last occurrence of the string "example" starting from the 10th character:

var str="I am from example,welcome to example site."; var n=str.lastIndexOf("example", 9);

nOutput:

-1

Try it Yourself »

String 对象参考手册JavaScript String Object

Other Extensions