The URL Object
By Flavio
Published · Updated
Tagged: Web Platform
Learn how to use the JavaScript URL object, from creating blob URLs with URL.createObjectURL to parsing a URL with the constructor to read its parts.
URL is a namespace used to host 2 static methods used to manipulate URLs using Blobs:
URL.createObjectURL()URL.revokeObjectURL()
Given a blob, you generate a URL to it using the URL.createObjectURL() function:
const myURL = URL.createObjectURL(aBlob)
Once you have the blob URL, you can destroy it from memory using:
URL.revokeObjectURL(myURL)
In addition to this, URL offers a very different functionality through its constructor, which can be used to create a URL. You can call it like this:
const currentUrl = new URL(window.location.href)
Now currentUrl has a set of properties you can use to inspect the URL:
hashthe hash fragmenthostthe domain + porthostnamethe domainhrefcontains the entire URLoriginscheme + domain + portpasswordpathnameportprotocolsearchsearchParamsusername
which are the usual parts of a URL.
Paste any URL below to see each property labeled:
You can alter most of those properties, then read the new URL string from href or by calling toString(). origin is read-only.
searchParams is a bit special. You cannot reassign the property itself, but it points at a live URLSearchParams object. Changing that object (with append(), set(), delete(), or sort()) updates the URL:
const currentUrl = new URL('https://test.com/hello?name=roger')
currentUrl.searchParams.append('age', '20')
currentUrl.searchParams.set('name', 'flavio')
currentUrl.href //'https://test.com/hello?name=flavio&age=20'Want me to talk about your product? You can sponsor this site.
Related posts about platform: