The JavaScript lastIndexOf method returns the final index of a specified value within a string or an array. If the value does not exist, it will yield -1.
NOTE: The string is searched from the end to the beginning, but returns the index starting from the beginning, at position 0.
The lastIndexof method is case sensitive.
Syntax:
Example
array.lastIndexOf(value, start)
Parameters:
Value: The initial parameter represents the value that will be sought within the array.
Start: This denotes the location from which the search will commence. In the absence of a specified value in the argument, the default setting is the length of the array.
Return value:
Indicating the position of the element where the specified value appears for the final time, or returning -1 if the value is not present.
Browser Support:
| Chrome | Yes |
|---|---|
| Safari | Yes |
| Firefox | Yes |
| Opera |
Example
JavaScript lastIndexOf Method
Example
<script type="text/javascript">
// JavaScript to illustrate lastIndexOf() method
function pyVisualizer() {
// string
var str = 'Example';
//Finding the index of the string
var index = str.lastIndexOf('T');
document.write(index);
}
runExample();
// expected output: arr[Output:4]
</script>
Output:
Example 2
JavaScript lastIndexOf Method
Example
<script type="text/javascript">
// JavaScript to illustrate lastIndexOf() method
function pyVisualizer() {
// string
var str = 'Example';
//Finding the index of the string
var index = str.lastIndexOf('s');
document.write(index);
}
runExample();
// expected output: arr[Output:-1]
</script>
Output: