JavaScript lastIndexOf method entry example (calculates the last occurrence of a specified character in a string)
- 2020-03-30 04:09:06
- OfStack
JavaScript lastIndexOf method
The lastIndexOf method calculates the last occurrence of the specified string in the entire string and returns the value. The syntax is as follows:
str_object.lastIndexOf( search, start )
Parameter description:
parameter | instructions |
---|---|
str_object | String (object) to manipulate |
search | A necessity. The string to retrieve |
start | Optional. Specifies where to start the retrieval, and if the parameter is omitted, the retrieval begins with the last character of the string |
Tip: strings are counted from 0.
Example of the lastIndexOf method
<script language="JavaScript">
var str = "www.jb51.net";
document.write( str.lastIndexOf( "." ) + "<br />" );
document.write( str.lastIndexOf( ".", 5 ) + "<br />" );
document.write( str.lastIndexOf( ".", 10 ) );
</script>
Run the example and output:
9
3
9
Note that in the example above where the second argument is 5, what is actually found is the first. Symbol, which is a search in the www.5 string.
LastIndexOf is case-sensitive and returns -1 if the string value to be retrieved does not appear.