jQuery JavaScript lastIndexOf()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16258684/
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-08-26 16:49:07  来源:igfitidea点击:

JavaScript lastIndexOf()

javascriptjquery

提问by paradise_lost

In C# I can do this

在 C# 中,我可以做到这一点

string ID = "ContentPlaceHolderDefault_MainSiteSectionArea_MyPagePlaceHolder_Item4_FavoritAmusementCalender_6_deleteRight_2"; ??
ID = ID.Substring(ID.LastIndexOf("_") + 1);?

to return the last int 2

返回最后一个 int 2

How can I most easily do this in jQuery/JavaScript

我怎样才能最容易地在 jQuery/JavaScript 中做到这一点

The id is created dynamic and can for now be up to 3 digit.

id 是动态创建的,现在最多可以是 3 位数字。

Thanks in advance.

提前致谢。

回答by sgeddes

You were close -- just case sensitive:

你很接近——只是区分大小写:

ID = ID.substring(ID.lastIndexOf("_") + 1);

JS Fiddle Example

JS小提琴示例

回答by paxdiablo

JavaScript also has a lastIndexOf()method, see here. You can therefore use:

JavaScript 也有一个lastIndexOf()方法,见这里。因此,您可以使用:

var str1 = "Blah, blah, blah Calender_6_deleteRight_272";
var str2 = str1.substr (str1.lastIndexOf ("_") + 1);

This gives you 272.

这给你272

Keep in mind that, if the string doesn'tcontain an underscore, you'll get the original string back in its entirety. That may or may not be desired in your specific case - you can check the result of the lastIndexOf()call against -1to detect this.

请记住,如果字符串包含下划线,您将恢复完整的原始字符串。在您的特定情况下可能需要也可能不需要 - 您可以检查lastIndexOf()调用的结果-1来检测这一点。

回答by s3m3n

You should do this with:

你应该这样做:

function get_last_part(str){
    var split = str.split('_');
    return split[split.length-1];
}
console.log(get_last_part("ContentPlaceHolderDefault_MainSiteSectionArea_MyPagePlaceHolder_Item4_FavoritAmusementCalender_6_deleteRight_2")); // this will write "2" in console

In this way you will get always result and you don't need to concern about out of index problems. This will return always last part of your string, if it doesn't have _you will get first part of it.

通过这种方式,您将始终获得结果,而无需担心索引不足的问题。这将始终返回字符串的最后一部分,如果没有,_您将获得它的第一部分。

console.log(get_last_part("Content")); // will write "Content" into console

回答by Niet the Dark Absol

Have you tried str.substr(-1)?

你试过str.substr(-1)吗?