The window.location object describes the current document URL and can also navigate or reload the current browsing context. Because window.location and location refer to the same object in a normal page, either form is commonly seen.
console.log(location.href);
console.log(location.hostname);
| Property | What it returns |
|---|---|
location.href | The complete URL string. |
location.protocol | The URL scheme, such as https:. |
location.host | Hostname plus port when a port is present. |
location.hostname | The hostname only, without the port. |
location.port | The explicit port string, or an empty string when the default port is used. |
location.pathname | The path beginning with /. |
location.search | The query string beginning with ?, or an empty string. |
location.hash | The fragment beginning with #, or an empty string. |
location.origin | The URL origin: protocol, host and port where applicable. |
The original two working demonstrations remain available. Each demo displays the values and includes complete source users can copy.
DEMO: Output of Location properties with code
DEMO: Output of all Location properties from a full URL with code
location.href to get and work with the full URL
location.hostname to get the hostname
location.reload() to refresh the current page
| Method | Purpose and working demo |
|---|---|
location.assign() | Loads the supplied URL and normally keeps the current page in session history. |
location.reload() | Reloads the current URL. |
location.replace() | Loads a replacement URL without keeping the current page as a session-history entry. The original demo page supplies its own return link because the Back button cannot return to this entry after replacement. |
location.toString() | Returns the complete URL as a string. |
Use assign() when normal navigation history is desirable. Use replace() when the current entry should be replaced, such as an intermediate redirect page that the user should not return to with Back.
location represents the active page and can trigger navigation. If you only need to parse or construct a URL without navigating, create a URL object instead.
const url = new URL(location.href);
console.log(url.pathname);
console.log(url.searchParams.get('q'));
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.