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
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);
I love the new array methods like filter so there is a demo with using this
let o = 'www.example.com/products/cream/handcreamproduct1'.split('/').filter(function(elm, i, arr){
if(i>arr.length-3){
return elm;
}
});
console.log(o);
There is no built in array function to do that.
Instead use
const urlParts = 'url'.split('/');
return urlParts[urlParts.length - 2] + "/" + urlParts[urlParts.length - 1];
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