Reputation: 119
In C# I can do this
string ID = "ContentPlaceHolderDefault_MainSiteSectionArea_MyPagePlaceHolder_Item4_FavoritAmusementCalender_6_deleteRight_2";
ID = ID.Substring(ID.LastIndexOf("_") + 1);
to return the last int 2
How can I most easily do this in jQuery/JavaScript
The id is created dynamic and can for now be up to 3 digit.
Thanks in advance.
Upvotes: 5
Views: 25837
Reputation: 4197
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
Upvotes: 0
Reputation: 881173
JavaScript also has a lastIndexOf()
method, see here. You can therefore use:
var str1 = "Blah, blah, blah Calender_6_deleteRight_272";
var str2 = str1.substr (str1.lastIndexOf ("_") + 1);
This gives you 272
.
Keep in mind that, if the string doesn't contain 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 -1
to detect this.
Upvotes: 5
Reputation: 62831
You were close -- just case sensitive:
ID = ID.substring(ID.lastIndexOf("_") + 1);
Upvotes: 13