Course recommendation:
- Föregående sida indexOf()
- Nästa sida length
- Åter till föregående nivå JavaScript String referens manual
JavaScript String lastIndexOf() method
lastIndexOf()
Definition and usage
lastIndexOf()
The method returns the index (subscript) of the last occurrence of the specified value in the string.
lastIndexOf()
The method searches for the string from the beginning.
The method returns the index from the beginning (position 0). lastIndexOf()
If the value is not found, then The position of the search value. Number
.
lastIndexOf()
The method returns
The method distinguishes between uppercase and lowercase.
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.";
Try it yourself
stringSyntaxsubstring, start)
.lastIndexOf(
.lastIndexOf( | Optional. Starting position. |
---|---|
substring | , |
start |
) Parameter |
-1
Required. The string to be searched. | Optional. Starting position. |
---|---|
Default value is the length of the string. |
Type Description |
If it does not appear, return
-1
If in string Technical details start Return value substringexists in substring position before substringIf not found, return -1.
Description
lastIndexOf()
method searches for the substring from the end to the beginning in the string string, to see if it contains the substring substring. The starting position of the search is in the string string of start at or string end (not specified start parameter). If a substringthen the lastIndexOf() method will return substring If the last character of the string The first character of the found one is in substring is actually string The position in which it appears start The last one before substring.
If in string is not found substringIf the method does not find it, it returns -1.
Note:Although lastIndexOf()
The method searches for the string from the end to the beginning, but the character position it returns is still calculated 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()
It is ECMAScript1 (ES1) feature.
All web browsers fully support ES1 (JavaScript 1997):
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Stöd | Stöd | Stöd | Stöd | Stöd | Stöd |
- Föregående sida indexOf()
- Nästa sida length
- Åter till föregående nivå JavaScript String referens manual