JavaScript lastIndexOf ()

In C #, I can do it

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 do this in jQuery / JavaScript

The identifier is created dynamically and can now be up to three digits.

Thanks in advance.

+5
source share
4 answers

You were close - just case sensitive:

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

JS script example

+12
source

JavaScript also has a method lastIndexOf(), see here . Therefore you can use:

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

It gives you 272.

, , . - lastIndexOf() -1, .

+5

Have you tried str.substr(-1)?

0
source

You have to do it 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

This way you always get the result, and you don’t have to worry about index issues. This will always return the last part of your string; if it does not _, you will get its first part.

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

All Articles