JavaScript Window Location Object

Complete guide to all properties and methods of the location object for URL manipulation and navigation

Location Properties

All properties of the window.location object

🔗
href
location.href
Loading...
Complete URL string - Gets or sets the entire URL. Setting this property navigates to the new URL.
🔒
protocol
location.protocol
Loading...
Protocol scheme - The web protocol used (http:, https:, file:, etc.). Includes the colon.
🌐
host
location.host
Loading...
Hostname and port - The server's domain name or IP address, including port number if specified.
🏷️
hostname
location.hostname
Loading...
Domain name - The server's domain name or IP address, without the port number.
🎯
port
location.port
Loading...
Port number - The port number of the URL. Returns empty string if using default port (80 for HTTP, 443 for HTTPS).
📁
pathname
location.pathname
Loading...
Path and filename - The path component of the URL, starting with a forward slash (/).
🔍
search
location.search
Loading...
Query string - The query string portion of the URL, including the leading question mark (?).
#️⃣
hash
location.hash
Loading...
Fragment identifier - The anchor part of the URL, including the hash sign (#). Used for page anchors.
🏁
origin
location.origin
Loading...
Origin - The protocol, hostname, and port number combined. Read-only property.

URL Structure Visualization

URL Breakdown

Location Methods

assign()
location.assign(url)

Loads a new document. Similar to setting location.href, but can be called as a method.

replace()
location.replace(url)

Replaces the current document with a new one. Removes current page from history.

reload()
location.reload(forceReload)

Reloads the current document. Use true to bypass cache.

toString()
location.toString()

Returns the string representation of the URL (same as location.href).

// Example: Complete URL Manipulation

// 1. Get current URL parts
const url = {
  full: location.href,
  protocol: location.protocol,
  host: location.host,
  path: location.pathname,
  query: location.search,
  hash: location.hash
};

// 2. Navigate to new page (preserves history)
function goToPage(path) {
  location.assign(path);
}

// 3. Redirect without history
function redirectTo(path) {
  location.replace(path);
}

// 4. Update query parameters
function updateQueryParams(params) {
  const url = new URL(location.href);
  Object.entries(params).forEach(([key, value]) => {
    url.searchParams.set(key, value);
  });
  location.href = url.toString();
}

// 5. Scroll to anchor
function scrollToAnchor(anchorId) {
  location.hash = anchorId;
}

Practical Examples & Experiments

Navigation History & URL State

History length: 0

Experiment results will appear here...

Create Your Own URL

Custom URL will appear here...