Explain Codes LogoExplain Codes Logo

How do I parse a URL into hostname and path in javascript?

javascript
url-object
relative-urls
regex
Alex KataevbyAlex Kataev·Feb 13, 2025
TLDR

When it comes to separating the hostname and path from a URL, the URL object in JavaScript is your best partner:

const url = new URL('http://www.example.com/path'); console.log(url.hostname); // Outputs 'www.example.com', quite the host, huh? console.log(url.pathname); // Spits out '/path', the road less traveled

You get the components instantly, no need for extra code or wrestling with regex. Straight from the horse's.. I mean, the URL's mouth.

How to deal with relative URLs

Working with relative URLs? No sweat! Specify the base URL as the second argument:

const url = new URL('/path', 'http://www.example.com'); console.log(url.hostname); // Still 'www.example.com', the host with the most console.log(url.pathname); // Pushes '/path', not a garden path, promise!

Ensures your relative URLs don't feel lost without their base.

Tapping into other components

The URL object is like an onion; it's got layers. Besides hostname and path, you can dig deeper and parse other components such as protocol, port, query strings (search), even hash fragments! All that without chopping additional logic into the mix:

const url = new URL('http://www.example.com:80/path?query=123#hash'); console.log(url.protocol); // 'http:', smooth as protocol console.log(url.host); // 'www.example.com:80', not a party without a host, right? console.log(url.port); // '80', no port in a storm console.log(url.search); // '?query=123', Sherlock would be proud console.log(url.hash); // '#hash', great addition to sky-high URL pies

Another path to enlightenment: the anchor element

Sometimes the URL object won't cut it. Maybe you need to support vintage browsers, or you're a nostalgic soul. Then, create an anchor element (<a>), set its href to your heart's URL:

const anchor = document.createElement('a'); anchor.href = 'http://www.example.com/path'; console.log(anchor.hostname); // Serves you 'www.example.com', still the star of the show console.log(anchor.pathname); // Reveals '/path', path to enlightenment!

Let DOM do the heavy lifting behind the scene.

Harnessing Regex: When DOM methods don't suffice

In non-browser environments or when absolute control is your jam, go for regex to parse URLs:

const regex = /^(https?):\/\/([^\/\s]+)(\/\S*)?$/; const matches = 'http://www.example.com/path'.match(regex); console.log(matches[1]); // 'http', clean as a hattrick console.log(matches[2]); // 'www.example.com', the belle of the ball console.log(matches[3]); // '/path', the only way is forward!

Craft your regex smartly. Handle different formats and possible gremlins (whoops, I mean edge cases).

Ensuring your code plays nice with all browsers

Not all browsers grew up in the same neighborhood. Older dudes may not know about the URL object. Test your code in different electronic alleys for compatibility. URL object acting shy? Use a fallback, go to DOM method or bring regex as a trusty sidekick.

No passenger left behind: Query parameters

Our train is hauling a lot of query passengers. Each passenger (parameter) has their own ticket (name and value):

const url = new URL('http://example.com/train?passenger=John&seat=22'); console.log(url.searchParams.get('passenger')); // John, the Beatles fan console.log(url.searchParams.get('seat')); // 22, not just a number!

With the URL object, no passenger is left behind at the station!

Hustle with URL parameters

Got a URL with a query party going on? No worries, just roll-call all the parameters like a school teacher:

for (const [key, value] of url.searchParams) { console.log(`${key}: ${value}`); }

Now you have a headcount of all passengers (parameters) in your URL train.

Deciding your parsing strategy

Wondering which roadmap should you follow to parse URLs?

  • Modern browsers & Node.js: The URL object, powerful and efficient.
  • Vintage Browser Support: Create an <a> element, the old charm never fails.
  • Non-browser environments: Unleash the regex beast, for its predictability across environments.