JavaScript Location Object

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);
Table of Contents

Location properties Top ↑

PropertyWhat it returns
location.hrefThe complete URL string.
location.protocolThe URL scheme, such as https:.
location.hostHostname plus port when a port is present.
location.hostnameThe hostname only, without the port.
location.portThe explicit port string, or an empty string when the default port is used.
location.pathnameThe path beginning with /.
location.searchThe query string beginning with ?, or an empty string.
location.hashThe fragment beginning with #, or an empty string.
location.originThe URL origin: protocol, host and port where applicable.

Property demos Top ↑

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

Focused Location tutorials

location.href to get and work with the full URL

location.hostname to get the hostname

location.reload() to refresh the current page

Location methods Top ↑

MethodPurpose and working demo
location.assign()Loads the supplied URL and normally keeps the current page in session history.
location.assign('site_map.php');
location.reload()Reloads the current URL.
location.reload();
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.replace('location-demo.php');
location.toString()Returns the complete URL as a string.
alert(location.toString());

assign() vs replace() Top ↑

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 and the URL object Top ↑

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'));

Window Object Document Object




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer