JS Get Second To Last Index Of

后端 未结 2 992
半阙折子戏
半阙折子戏 2021-01-03 22:08

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         


        
相关标签:
2条回答
  • 2021-01-03 22:49

    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('/');
    
    0 讨论(0)
  • 2021-01-03 23:06

    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.
    
    0 讨论(0)
提交回复
热议问题