In this post we will be covering how to get the last segment of a URL in JavaScript with as little technical jargon as possible so you will have everything you need right here without having to look any further!
In JavaScript you have the ability to get the current URL and split it into sections to display different data depending on the URL paths amongst many other use cases.
To be able to do this though you will need to be able to extract the various segments on a URL in JavaScript which is what we will be covering in this post.
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).
How to get the last segment of a URLin JavaScript
To get the last segment or path of a URL in JavaScript is fairly easy to do by using a combination of different methods that mainly involve splitting the URL using the /
(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:
window.location.pathname.split("/");
// ["", "blog", "javascript", "how-to-get-the-last-segment-of-a-url-in-javascript", ""]
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:
window.location.pathname.split("/").filter(entry => entry !== "");
// ["blog", "javascript", "how-to-get-the-last-segment-of-a-url-in-javascript"]
And then the final step to get the last segment of the URL in JavaScript will be to get the last entry in the array.
We can do this by first finding the length of the array and subtracting 1 because of how indexes start at 0.
Here is the complete example of how to get the last segment of a URL in JavaScript:
const { pathname } = window.location;
const paths = pathname.split("/").filter(entry => entry !== "");
const lastPath = paths[paths.length - 1];
console.log(lastPath); // how-to-get-the-last-segment-of-a-url-in-javascript
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.
How to get the last segment of a URL in JavaScript using substrings and slice
To get the last segment of a URL in JavaScript using substrings, all we need to do is to take the substring after the last /
character.
The method we will be using to get substrings in JavaScript is String.prototype.slice.
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:
const { pathname } = window.location;
let trimmedPathname = pathname;
if (pathname.endsWith("/")) {
trimmedPathname = pathname.slice(0, pathname.length - 1);
}
console.log(trimmedPathname.slice(trimmedPathname.lastIndexOf("/") + 1));
// how-to-get-the-last-segment-of-a-url-in-javascript
As you can see we first check for a trailing slash, and if it exists with String.prototype.endsWith then we remove it using String.prototype.slice to select the rest of the string.
We then go onto use slice again to get the last path or segment of the URL.
How to remove the last part of URL in JavaScript
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.
Here is how we can remove the last part of URL in JavaScript:
const { pathname } = window.location;
const paths = pathname.split("/").filter(entry => entry !== "");
paths.pop(); // how-to-get-the-last-segment-of-a-url-in-javascript
const newPathname = `/${paths.join("/")}/`;
console.log(newPathname); // "/blog/javascript/"
Summary
There we have how to get the last segment of a URL in JavaScript, if you want more like this be sure to check out some of my other posts!