JavaScript document.URL and the Current Page Address

document.URL returns the complete URL of the current document as a string.

const pageUrl = document.URL;
console.log(pageUrl);

window.location.href (usually shortened to location.href) also exposes the current address. The location object is especially useful when you need individual URL parts.

Table of Contents

Read the URL with document.URL Top ↑

const currentUrl = document.URL;

The property name is case-sensitive: use URL, not url.

Current document URL:

Use location.href and Individual URL Parts Top ↑

console.log(location.href);      // complete address
console.log(location.origin);    // scheme + host + port
console.log(location.hostname);  // hostname only
console.log(location.pathname);  // path
console.log(location.search);    // query string
console.log(location.hash);      // fragment

When you only need the host name, prefer location.hostname rather than the deprecated document.domain API. See the document.domain tutorial for legacy behavior.

Parse the Address with the URL Object Top ↑

The URL class is useful when you want a reusable object representing an address.

const url = new URL(document.URL);
console.log(url.hostname);
console.log(url.pathname);
console.log(url.searchParams.get("id"));

Display the URL on the Page Top ↑

The original example used document.write(). For normal page output, write into an existing element instead:

const output = document.getElementById("urlOutput");
output.textContent = document.URL;

This avoids the parsing and page-replacement problems associated with document.write().

Common Mistakes Top ↑

  • document.URL is a string; use new URL(...) if you need convenient parsing methods.
  • Do not manually split a URL on /, ?, or # when the URL API can parse it reliably.
  • Remember that changing location.href navigates the browser; reading it does not.
document Object document.lastModified


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