JavaScript lastIndexOf() 方法
Definition and Usage
The lastIndexOf() method returns the last occurrence of a specified string value, searching backwards and forwards at the specified position in a string.
grammar
stringObject.lastIndexOf(searchvalue,fromindex)Parameter Description
searchvalue | Required. Specifies the string value to retrieve. |
fromindex | Optional integer parameter. Specifies the position in the string at which to start searching. Its legal values are 0 to stringObject .length - 1. If this parameter is omitted, the search will start at the last character of the string. |
return value
If searchvalue exists before the fromindex position in stringObject , then the position of the last searchvalue that occurs is returned .
illustrate
This method will retrieve the string stringObject from end to end to see if it contains the substring searchvalue . The position to start searching is at the fromindex of the string or the end of the string (when fromindex is not specified ). If a searchvalue is found, returns the position in stringObject of the first character of searchvalue . Character positions in stringObject are 0-based.
Tips and Notes
NOTE: The lastIndexOf() method is case sensitive!
Note: This method returns -1 if the string value to be retrieved does not appear.
Example
In this example, we will do different searches within the "Hello world!" string:
<script type="text/javascript"> var str="Hello world!" document.write(str.lastIndexOf("Hello") + "<br />") document.write(str.lastIndexOf("World") + "<br />") document.write(str.lastIndexOf("world")) </script>
Output of the above code:
0 -1 6