.split('/') to split the URL string into an array of each part, then use
.at(-1) to get the last part from the array.
split() method takes a character and splits a string into an array of substrings that were separated by that character in the string. A URL’s segments are separated by the
/ character, so we pass this character to
split() to create an array with each URL segment as an element.
After getting this array, we use the
at() method to get a single element from it.
at() is a new ES2022 addition that accepts both positive and negative integers.
Passing negative integers to
at() makes it count from the end of the array, so
-1 gives the first element from the end (last element) – the last part of the URL.
Remove last part of URL
You might be getting the last part of the URL to remove it from the URL string. If that’s what you want, there’s no need to get the last part of the URL at all – we can remove it easily with the
We use the
lastIndexOf() method to get the position of the last occurrence of the
/ character, because this is the point just before the last part of the URL starts in the string.
slice() returns the portion of a string between specified start and end indexes, passed as the first and second arguments respectively. We pass
0 as the first argument so the resulting substring starts from the first character, and we pass the result of
lastIndexOf() as the second argument so that the substring ends at the index before the last part of the URL starts in the string.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.