javascript JS 获取倒数第二个索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25331030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:22:20  来源:igfitidea点击:

JS Get Second To Last Index Of

javascript

提问by Nicolas

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.com/website/projects/2

I currently get the number 2by using

我目前2使用

$(location).attr('href').substring($(location).attr('href').lastIndexOf('/')+1);

$(location).attr('href').substring($(location).attr('href').lastIndexOf('/')+1);

But what if I want to get the word projects?

但是如果我想得到这个词projects呢?

Can anybody help me out with this? Thanks in advance!

有人可以帮我解决这个问题吗?提前致谢!

回答by antyrat

You can use splitmethod:

您可以使用split方法:

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

回答by Rahul R.

Without using split, and a one liner to get the 2nd last index:

不使用 split 和 one liner 来获得倒数第二个索引:

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.

感谢@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:

可以和 lastIndexOf 一样使用:

url.nthLastIndexOf('/', 2);
url.nthLastIndexOf('/', 3);
url.nthLastIndexOf('/');