Skip to main content Accessibility Feedback

How to use the URL API with vanilla JS

The URL API is a browser API that lets you create a URL object from a string that you can then parse and manipulate.

Confused? Let’s dig in and demystify this a bit.

Creating a URL from a string with vanilla JS

To create a new URL object, pass the URL as a string into the new URL() constructor method.

var url = new URL('');

I’m using a comically complex example above so that you can see all of the cool stuff the URL API lets you do.

Parsing a URL with the URL API

The new URL() constructor returns an object with same properties as a the window.location property.

// The hash or anchor link on the URL
// returns "#contact"

// The root domain of the URL
// returns ""

// The full URL
// returns ""

// The root domain, including the protocol
// returns ""

// The path on the URL
// returns "/about"

// The protocol on the URL
// returns "https:"

// The query strings (as a string) on the URL
// returns "?num=42&greeting=hello";

Here’s a demo.

Updating values on a URL

You can use those same properties to update the values of a URL.

For example, if you wanted to change the hash from #contact to #photo, you would do this.

url.hash = 'photo';

Here’s another demo.

Browser support

The URL API works in all modern browsers, but not IE. You can push support back to IE9 with a polyfill.