Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS Get Second To Last Index Of

Tags:

I am trying to figure out how to get the second to last index of a character in a string.

For example, I have a string like so:

http://www.example.com/website/projects/2 

I currently get the number 2 by using

$(location).attr('href').substring($(location).attr('href').lastIndexOf('/')+1);

But what if I want to get the word projects?

Can anybody help me out with this? Thanks in advance!

like image 693
Nicolas Avatar asked Aug 15 '14 17:08

Nicolas


People also ask

How would you access the 2nd to last element in an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.

How do you find the last index of a character in a string in JS?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

What is IndexOf and lastIndexOf?

The IndexOf and LastIndexOf may be used to locate a character or string within a string. IndexOf finds the first occurrence of a string, LastIndexOf finds the last occurrence of the string. In both cases, the zero-based index of the start of the string is returned.

How do you find last index?

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 can use split method:

var url = $(location).attr('href').split( '/' ); console.log( url[ url.length - 1 ] ); // 2 console.log( url[ url.length - 2 ] ); // projects // etc. 
like image 195
antyrat Avatar answered Oct 17 '22 20:10

antyrat


Without using split, and a one liner to get the 2nd last index:

var secondLastIndex = url.lastIndexOf('/', url.lastIndexOf('/')-1) 

The pattern can be used to go further:

var thirdLastIndex = url.lastIndexOf('/', (url.lastIndexOf('/', url.lastIndexOf('/')-1) -1)) 

Thanks to @Felix Kling.

A utility function:

String.prototype.nthLastIndexOf = function(searchString, n){     var url = this;     if(url === null) {         return -1;     }     if(!n || isNaN(n) || n <= 1){         return url.lastIndexOf(searchString);     }     n--;     return url.lastIndexOf(searchString, url.nthLastIndexOf(searchString, n) - 1); } 

Which can be used same as lastIndexOf:

url.nthLastIndexOf('/', 2); url.nthLastIndexOf('/', 3); url.nthLastIndexOf('/'); 
like image 24
Rahul R. Avatar answered Oct 17 '22 20:10

Rahul R.