Javascript – Array.pop – last two elements – JavaScript

arraysjavascripturl

I have a question using Array.pop function in JavaScript. Array.pop removes and returns the last element of an Array. My question is then: is it possible to remove and return the last TWO elements of array and return them instead of the last?

I am using this function to return the last element of URL, like this:

URL: www.example.com/products/cream/handcreamproduct1

'url'.splice("/").pop(); -----> "handcreamproduct1"

what i want is:

'url'.splice("/").pop(); -----> "cream/handcreamproduct1"

I want to take the last two parameters in the url and return them, with .pop i only get the last one. Remember that the URL is dynamic length. The url can look like this:

URL: www.example.com/products/cream/handcreamproduct1
OR

URL: www.example.com/products/handcream/cream/handcreamproduct1

Best Answer

Split the array, use Array#slice to get the last two elements, and then Array#join with slashes:

var url = 'www.example.com/products/cream/handcreamproduct1';

var lastTWo = url
  .split("/") // split to an array
  .slice(-2) // take the two last elements
  .join('/') // join back to a string;

console.log(lastTWo);