To get the current URL in JavaScript, you need to reference the window.location.href
property of the Window.location
object. This will return the full URL of the current page, with all URL parameters and URL fragments.
The window
object, in case you’re just getting started with JavaScript and coming across it for the first time, is a global object that represents the window that the page is displayed in.
It’s the parent object of all other elements on the web page and it gives you, the developer, access to many important JavaScript features and functions, such as the Document Object Model (DOM), the browser’s navigational and history objects, and others. In this case, we’re explicitly interested in the window
object’s location.href
property.
Here’s the property’s syntax:
window.location.href
And here’s an example for how to use it:
const theUrl = window.location.href;
console.log(theUrl) // Logs current URL
If you need to get other parts of the URL, you can also store the value of the window.location
property in a constant and reference its properties just like you would reference the properties of the Window
object:
const theLocation = window.location;
console.log(theLocation.href) // Logs current URL
console.log(theLocation.host) // Logs current domain and port
console.log(theLocation.hostname) // Logs current domain without port
console.log(theLocation.pathname) // Logs current page path
console.log(theLocation.search) // Logs current URL parameters
console.log(theLocation.search) // Logs current URL fragments
This gives you a lot of Location
data to work with — you can also get the domain name, the page path, the URL parameters, and URL fragments without needing to manipulate the full URL.
Why Store It in a Variable First
If you need to reference the value of window.location.href
multiple times, there could be benefits to storing it in a variable or constant. When you store a value in one, it’s saved to the memory and it can be accessed much faster than if you had to retrieve it from the window
object every time you need it.
Additionally, using a variable makes your code much more readable and maintainable, as it’s clear to you and everyone else who needs to read your code what the value represents. And if you need to change it in the future, you only need to change it in one place.