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.
lastIndexOf() The lastIndexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the last occurrence of the specified substring.
The indexOf() and lastIndexOf() function return a numeric index that indicates the starting position of a given substring in the specified metadata string: indexOf() returns the index for the first occurrence of the substring. lastIndexOf() returns the index for the last occurrence of the substring.
The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .
You were close -- just case sensitive:
ID = ID.substring(ID.lastIndexOf("_") + 1);
JS Fiddle Example
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With