JS Get Second To Last Index Of

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('/');

You can use split method:

var url = $(location).attr('href').split( '/' );
console.log( url[ url.length - 1 ] ); // 2
console.log( url[ url.length - 2 ] ); // projects
// etc.

Tags:

Javascript