Recently I came across a scenario where I had to get the file extension from a URL and also from the file path.
The first thing which came to my mind was to use split() and then take the last item from the array.
But I wanted to do this in one line. So that is when I found out about pop() which returns the last element in the array.
url = http://xy.com/blob/somefile.pdf
filePath= c:\somefolder\somefile.txt
ext1 = url.split(".").pop()
ext2 = filePath.split(".").pop()
The pop()
method removes the last element from an array and returns that element. This method changes the length of the array.
The pop()
method removes (or pops) the last element in a given array. The method makes a change to the original array itself by this removal action. Finally, the method returns the removed element to us.
This method is intentionally generic. It is so as to ensure that this method can be applied or called to objects resembling arrays.
If you call pop()
in an empty array, it returns undefined.
References
https://www.w3schools.com/jsref/jsref_pop.asp