Course recommendation:

JavaScript String lastIndexOf() method

lastIndexOf() Definition and usage

lastIndexOf() method returns the index (subscript) of the last occurrence of the specified value in the string.

lastIndexOf() method searches for the string from the beginning.

method returns the index from the beginning (position 0). lastIndexOf() if the value is not found, then -1.

lastIndexOf() method returns

method is case-sensitive.

See also:

indexOf() method

Instance

Example 1

Search for the last occurrence of "planet" starting from position 20:
Search for the last occurrence of "planet":

let result = text.lastIndexOf("planet", 20);

Search for the last occurrence of "planet" starting from position 20:
let result = text.lastIndexOf("planet");

let result = text.lastIndexOf("planet", 20);

let result = text.lastIndexOf("Planet");

Example 2

Search for the last occurrence of "planet" starting from position 20:
let text = "Hello planet earth, you are a great planet.";

let result = text.lastIndexOf("planet", 20);

Try it yourself

stringSyntaxsubstring.lastIndexOf( start,

)

) Type
substring Parameter
start

Required. The string to be searched.

Optional. Starting position.

value

Default value is the length of the string. Type
Description

the position of the search value. Number

if it does not appear, then returns -1.

Technical details

value

If string returns start in substringexists before substring position. If the substring substringthen returns -1.

Description

lastIndexOf() method searches for the substring string from the end to the beginning, to see if it contains the substring substring. The starting position of the search is in the string string of start or string end (not specified start parameter). If a substringthen the lastIndexOf() method will return substring the first character in string due to the search from the end to the beginning of the string, the first substring is actually string position in start the last one before substring.

If string was not found substringthen this method returns -1.

Note:Although lastIndexOf() method searches for the string from the end to the beginning, but the character position it returns is still counted from the beginning. The position of the first character in the string is 0, and the position of the last character is string.length-1.

browser support

lastIndexOf() is an ECMAScript1 (ES1) feature.

All browsers fully support ES1 (JavaScript 1997):

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support Support Support Support Support Support

Related Pages

JavaScript String

JavaScript String Methods

JavaScript String Search