Course contentsShow
← Web Development
Lesson 941 of 2,98217. URL and History ManagementFree lesson

Modifying URL Properties

Change URL components by setting properties on a URL object and understand the resulting string format.

Modifying URL Properties

What you'll learn: How to change parts of a URL by directly assigning new values to a URL object's properties.


Editing a URL is Like Filling Out a Form

Once you've created a URL object, you don't need to rebuild it from scratch to change something. Just like updating fields in a form, you can directly assign new values to any property of the URL object, and the full URL string automatically updates to reflect your changes.

How Property Assignment Works

After constructing a URL object, you can modify any component by setting its property:

const url = new URL('https://example.com/path?search=test');

// Change the hostname
url.hostname = 'newdomain.com';
console.log(url.href);
// 'https://newdomain.com/path?search=test'

// Change the pathname
url.pathname = '/new/path';
console.log(url.href);
// 'https://newdomain.com/new/path?search=test'

// Change the search parameters
url.search = '?id=42&type=user';
console.log(url.href);
// 'https://newdomain.com/new/path?id=42&type=user'

// Change the hash
url.hash = '#section2';
console.log(url.href);
// 'https://newdomain.com/new/path?id=42&type=user#section2'

The Result is Always Valid

When you modify URL properties, the browser automatically formats and encodes everything correctly. Special characters get encoded, slashes are preserved where needed, and the href property always gives you a properly formatted complete URL string.

Key Takeaway: You can modify any part of a URL object by directly assigning to its properties (hostname, pathname, search, hash, etc.), and the full URL string updates automatically with proper formatting.