Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use array.pop() twice in a row to get second last element

var path = document.location.pathName;
example.com/store/order/cats

Sometimes it might be:

example.com/store/order/cats/

Note the slash at the end.

I'd like a function to return cats in either case. If there is no trailing slash I go:

function() {
    return path.split('/').pop();
}

But if there is a trailing slash, I need to pop() twice. I tried this:

function() {
        return path.split('/').pop().pop();
    }

Which threw an error.

So the array arising from split('/') can be either:

["", "store", "order", "cats", ""] // trailing slash

or

["", "store", "order", "cats"] // no trailing slash

How can I return cats in either eventuality?

like image 947
Doug Fir Avatar asked Dec 07 '25 07:12

Doug Fir


1 Answers

As others have said, you could try removing the last character if it is a slash, and then using the first method.

function getLastWordInPathName() {
  var path = document.location.pathName.replace(/\/$/, '');
  return path.split('/').pop();
}

However, your question was asking why you can't call pop() twice.

The first time you call pop(), the value of the last element in the array is returned. When you call pop() again, this function is applied to the result of the previous function - so you are calling pop() on the string '/', and not on your array.

like image 50
Sam Avatar answered Dec 08 '25 21:12

Sam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!