The syntax is therefore the following: string.lastIndexOf (value, start).
The return value is a numeric value that represents the position of the last element’s position in the string, if there is more than one. If it doesn’t find this value, it returns -1.
As with indexOf, the value, i.e. the first argument passed as a parameter, can be a word, a number or a phrase. If more than one occurrence of this value is found, the method always returns the index of the last value found.
Instead the second parameter, beginning, is the starting point to search for the value. In some cases it may be necessary not to start from the beginning of the string. If start is not specified, it starts from position 0.
We use this method in a first example, where we take a string and search in it for the last occurrence of a word.
Here is a simple example:
var coding = 'Coding is fun and creative. Try coding yourself.'; var indexString = coding.lastIndexOf('coding'); console.log(indexString);
In the browser console we will see as a result 60, that is the position of the last word. If we had used indeOf we would have obtained 5, which is the position of the first word.
var coding = 'Coding is fun and creative. Try coding yourself.'; var indexString = coding.lastIndexOf('the coding'); console.log(indexString);
In the browser console we will therefore display the value -1.