I am trying to figure out how to get the second to last index of a character in a string.
For example, I have a string like so:
http://www.example.co
Without using split, and a one liner to get the 2nd last index:
var secondLastIndex = url.lastIndexOf('/', url.lastIndexOf('/')-1)
The pattern can be used to go further:
var thirdLastIndex = url.lastIndexOf('/', (url.lastIndexOf('/', url.lastIndexOf('/')-1) -1))
Thanks to @Felix Kling.
A utility function:
String.prototype.nthLastIndexOf = function(searchString, n){
var url = this;
if(url === null) {
return -1;
}
if(!n || isNaN(n) || n <= 1){
return url.lastIndexOf(searchString);
}
n--;
return url.lastIndexOf(searchString, url.nthLastIndexOf(searchString, n) - 1);
}
Which can be used same as lastIndexOf:
url.nthLastIndexOf('/', 2);
url.nthLastIndexOf('/', 3);
url.nthLastIndexOf('/');