Course contentsShow
← JavaScript
Lesson 2311 of 2,72347. Networking PrimitivesFree lesson

Accessing and Modifying URL Components

Work with URL properties like href, origin, pathname, and hash to read and modify different parts of a URL.

Accessing and Modifying URL Components

You'll learn how to read and update individual parts of a URL object using built-in properties like href, origin, pathname, and hash.

The Structure of a URL

Think of a URL like a mailing address with distinct sections: the street, city, zip code, and apartment number. Similarly, URLs have components like protocol, hostname, path, and hash. The URL object gives you direct access to each piece as a property, letting you read or modify them individually.

Reading URL Components

Once you have a URL object (using the URL constructor you learned earlier), you can access its parts:

const url = new URL('https://example.com:8080/products/shoes?color=blue#reviews');

console.log(url.href);     // 'https://example.com:8080/products/shoes?color=blue#reviews'
console.log(url.origin);   // 'https://example.com:8080'
console.log(url.protocol); // 'https:'
console.log(url.hostname); // 'example.com'
console.log(url.port);     // '8080'
console.log(url.pathname); // '/products/shoes'
console.log(url.search);   // '?color=blue'
console.log(url.hash);     // '#reviews'

Modifying URL Components

These properties aren't just read-only—you can assign new values to change parts of the URL:

const url = new URL('https://example.com/old-path');

url.pathname = '/new-path';
url.hash = '#section2';

console.log(url.href); // 'https://example.com/new-path#section2'

When you modify a component, the full href updates automatically to reflect the change. This makes URL manipulation clean and error-free—no manual string concatenation needed.

Common Properties

  • href: The complete URL string
  • origin: Protocol + hostname + port (read-only)
  • pathname: The path portion (e.g., /products/shoes)
  • hash: The fragment identifier (e.g., #top)
  • search: The query string (e.g., ?id=123)

Key Takeaway: URL objects expose each component as a property, allowing you to read or modify specific parts without messy string operations—simply access pathname, hash, search, or other properties directly.