javascript JS获取倒数第二个索引

5n0oy7gb  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(197)

我想弄清楚如何获得字符串中字符的倒数第二个索引。
例如,我有一个这样的字符串:

http://www.example.com/website/projects/2

我现在使用2来获得数字
$(location).attr('href').substring($(location).attr('href').lastIndexOf('/')+1);
但是如果我想得到单词projects呢?
有人能帮我吗?提前感谢!

k97glaaz

k97glaaz1#

你可以使用split方法:

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

ws51t4hk2#

不使用split,使用一行代码来获得倒数第二个索引:

var secondLastIndex = url.lastIndexOf('/', url.lastIndexOf('/')-1)

该模式可用于更进一步:

var thirdLastIndex = url.lastIndexOf('/', (url.lastIndexOf('/', url.lastIndexOf('/')-1) -1))

感谢@Felix Kling。

效用函数

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);
}

它可以像lastIndexOf一样使用:

url.nthLastIndexOf('/', 2); //2nd last index
url.nthLastIndexOf('/', 3); //3rd last index
url.nthLastIndexOf('/'); //last index

相关问题