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!
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.
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).
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.
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 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.
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('/');
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