get the second to last item of an array?

Step 1: Use split() Method to split the elements into an array.

var fragment_arr = fragment.split("/");

Step 2: Use slice(-2) Method to select last 2 element from array, the negative number to select from the end of an array.

var lastTwo = fragment_arr.slice(-2);

Step 3: lastTwo array contains last two elements of fragment_arr, now you can access like this

var element = lastTwo[0];
alert(element);

Short answer : you can combine step 2 and 3 like below

var element = fragment_arr.slice(-2)[0];
alert(element);

arr.at(-2); will do exaclty that - it returns last second item in an array.


const arr = [1,2,3,4];
arr.at(-2); // Returns 3

The at() method takes a positive or negative integer and returns the item at that index. Negative integers count back from the last item in the array.

Docs: Array/at


Not everything has to be done using jQuery.

In plain old javascript you can do:

var pg_url = array_fragment[array_fragment.length - 2]

Easier and faster :)


Looks like you can also use Javascript's slice method:

var path = 'a/b/c/d';
path.split('/').slice(-2, -1)[0]; // c

You can also think of "second to last element in the array" as "second element of the array reversed":

var path = 'a/b/c/d';
path.split('/').reverse()[1]; // c