Suppose you’re building a website or web application and, for some reason, you need to get the value of the page path of the current page.
What’s the best way to do that?
pathname property of the
Window.location.pathname, as explained at MDN Web Docs, is a read-only property that returns a
Location object with the path of the current page.
In this tutorial, I’ll show you exactly how to get the value of this property—and go over some real-world scenarios for its use.
How It Works
If you fired up your browser’s developer tools, opened the console, and referenced the following property of the
// Reference pathname property of window.location object window.location.pathname
You’d see that the value of the pathname property for this page is
The property, as you can see, contains only the value of the page path, not that of the domain name or of any URL parameters.
This property comes in particularly handy when you’re working on a multi-page website or your application and part of your business logic is determined by the page path.
Ways to Use It
Store It in a Constant or Variable
The simplest, most straightforward way to use the window.location.pathname property is to store its value in a constant or variable so that you can reference it later in your code:
// Store value of pathname in constant const pagePath = window.location.pathname; // Store value of pathname in a variable var pagePath = window.location.pathname;
var, you could also declare your variable with the
let statement. Variables declared with
let cannot be redeclared (only reassigned), and their scope is limited to the block between curly brackets (and all of its sub-blocks).
Combine It With the Domain Name
hostname property of the window.location object.
If you need to get a value of the domain name with the page path, you could concatenate the values of the
// Concatenate hostname and pathname const pageLocation = window.location.hostname + window.location.pathname;
If you did is in the console on this page, your constant would get a value of
Combine It With URL Parameters
Suppose you need to combine the page path with the URL parameters. You can do so by concatenating the values of the
// Concatenate hostname and pathname const pageLocation = window.location.pathname + window.location.search;
If you have stricter requirements, you could even concatenate the page path only with specific parameters from the URL.
Split It Into an Array
If you need to turn the page path into structured data, you can use the
Array.split() method to split it into an array:
const pageLocation = window.location.pathname.split('/');
When you do this, you will notice that the data element at index 0 is always an empty string. That’s because the page path starts with “/” and the
Array.split() method treats the beginning of the page path as an empty string.
Thank you for reading this far and I hope this tutorial helped you get the job done.