One of the main segments of a URL that is usually used to determine what to display amongst other things is the last segment of the UR (or path).
/ (forward slash) character.
Firstly though we need to access the URL path before we can separate the segments.
We can do this by simply calling
window.location.pathname to get the full pathname of the URL as a string.
At this point we have multiple options, the easiest to use and develop with that covers the most use cases is the String.prototype.split method.
The String.prototype.split method can be used to split a string into different parts by supplying a separator argument.
We can call this method on the string and then supply the
/ character as the separator which will then convert the full pathname into an array of path segments.
We can do this like so:
After we have this array we should then filter out any empty strings which could appear in this array if there are trailing slashes in the original URL’s pathname.
We can filter out the empty strings by using the Array.prototype.filter method which is designed for cases just like this where you want to remove certain elements from an array.
Here is how this would look:
We can do this by first finding the length of the array and subtracting 1 because of how indexes start at 0.
This solution is a fairly generic solution and involves quite a few loops, whilst generally you would want to avoid unnecessary loops where possible but there are situations where it is not the case.
Where a URL pathname is never going to be so large to the point there would be a noticeable difference between looping and alternative methods it won’t make a difference.
Also, in the solution above it reads well, and is very easy to follow along which will improve code readability and maintainability.
On top of this the solution covers an edge case that other solutions might not, which is the trailing slash.
With that said, let’s take a look at an alternative solution using substrings as well.
It is important to remember that first we will need to remove any trailing slashes to the pathname otherwise we might end up with an empty string.
Let’s take a look at an example of how we can do this:
We then go onto use slice again to get the last path or segment of the URL.
Following on from our first example using the String.prototype.split method, we can also remove the last part of the URL with ease.
All we need to do is pop the array and then join it back up to get a complete pathname without the last part of the URL.