Explain Codes LogoExplain Codes Logo

Get protocol, domain, and port from URL

javascript
url-api
web-workers
url-parsing
Anton ShumikhinbyAnton Shumikhin·Jan 17, 2025
TLDR

Get a handle on protocol, domain, and port swiftly in JavaScript utilizing the URL object:

const url = new URL('http://www.example.com:8080/path'); console.log(url.protocol); // Returns "http:", don't drop the soap... it's slippery ;) console.log(url.hostname); // Says "www.example.com" console.log(url.port); // Booms "8080" on your face

Lean on the properties of URL object for an effective extract.

Not all browsers are created equal. URL object works like a charm, but in some cases like Internet Explorer, window.location.origin isn't supported. We can't leave our explorer buddies behind, right? Fret not, here's a fallback:

if (!window.location.origin) { // Assembling the Avengers... or well, the origin! window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: ''); }

With this in place, you'll sleep better knowing you've got window.location.origin compatibility across all browsers.

Wrestle with query strings and parameters

Checking off the basics, we march ahead to URL query strings:

const url = new URL('http://example.com:8080/path?query=value'); // UFO spotted! Oh wait, it's just a query value console.log(url.searchParams.get('query')); // "value"

But, it can get hairy with more complex scenarios. searchParams to the rescue!

let params = {}; for (let [key, value] of url.searchParams) { // The meat and potatoes of our params platter params[key] = value; }

Queries? No problemas!

Get crafty with custom parsing

Let's roll up our sleeves to extract a part of the path or to mould a custom URL structure:

const url = new URL('http://www.example.com:8080/dir/subdir/page?query=value'); // We've got an axe to grind! Takes cares of those pesky slashes console.log(url.pathname.split('/')); // ["", "dir", "subdir", "page"]

This nifty array can be your guide through path segments or build breadcrumbs for a navigation menu.

Unleashing Web Workers generated URL API power

The URL object can be used inside Web Workers for resource-intensive URL parsing off the main thread:

// Web Worker speaking here self.onmessage = function(event) { // OK Google, get me the domain name let url = new URL(event.data); postMessage(url.hostname); };

The URL API proves its might again in a web workers context.