Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript lastIndexOf()

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.

like image 340
paradise_lost Avatar asked Apr 28 '13 01:04

paradise_lost


People also ask

What is lastIndexOf in Javascript?

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.

What are the differences between indexOf () and lastIndexOf ()?

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.

How do you find a specific character in a string Javascript?

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.

How do I get the last index of an array?

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 .


2 Answers

You were close -- just case sensitive:

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

JS Fiddle Example

like image 183
sgeddes Avatar answered Oct 03 '22 11:10

sgeddes


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.

like image 22
paxdiablo Avatar answered Oct 03 '22 11:10

paxdiablo