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.
Here’s the property’s syntax:
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
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
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.