Javascript String lastIndexOf()
can locate substrings within another string.
The lastIndexOf()
method begins looking from the end of the string.
It searches a string for a given substring and return the position.
It returns -1 if the substring isn't found.
str.lastIndexOf(searchValue[, fromIndex])
searchValue
- a string representing the value to search for. If searchValue
is an empty string, then fromIndex
is returned.fromIndex
- Optional, the index to start matching. The default value is +Infinity. If fromIndex
>= str.length, the whole string is searched.
If fromIndex
< 0, lastIndexOf()
treats it as 0.
let stringValue = "hello world"; console.log(stringValue.lastIndexOf("o")); // 7
This method accepts an optional second argument that indicates the position to start searching from.
The last IndexOf()
starts searching from the given position and continues searching toward the beginning of the string, ignoring everything between the given position and the end of the string.
let stringValue = "hello world"; console.log(stringValue.lastIndexOf("o", 6)); // 4