Categories
JavaScript Answers

How to Parse a URL into the Hostname and Path in JavaScript?

Spread the love

Sometimes, we want to parse a URL into the hostname and path parts with JavaScript.

In this article, we’ll look at how to parse a URL into the hostname and path parts with JavaScript.

Create an a Element

We can create an a element and set the href property of it to the URL we want to parse,

Then we can get the properties of it to get the parts we want.

For instance, we can write:

const parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=foo#hash";

console.log(parser.protocol)
console.log(parser.host)
console.log(parser.hostname)
console.log(parser.port)
console.log(parser.pathname)
console.log(parser.hash)
console.log(parser.search)
console.log(parser.origin)

protocol has the protocol, which is 'http:' .

host is the hostname and the port, which is 'example.com:3000' .

hostname is the hostname, which is 'example.com' .

port is the port, which is 3000.

pathname has the pathname, which is the path after the host, which is '/pathname/' .

hash has the hash, which is #hash .

search has the query string with the question mark before it, which is '?search=foo' .

origin has the protocol and host together, which is ‘ http://example.com:3000’ .

URL Constructor

The URL constructor lets us parse the parts of a URL without creating an a element.

For instance, we can write:

const url= new URL("http://example.com:3000/pathname/?search=foo#hash")

console.log(url.protocol)
console.log(url.host)
console.log(url.hostname)
console.log(url.port)
console.log(url.pathname)
console.log(url.hash)
console.log(url.search)
console.log(url.origin)

We pass the URL into the URL constructor, and we get the same results as before.

The URL constructor is available with most modern browsers.

Conclusion

To parse a URL with JavaScript, we can create an a element and set its href property.

Or we can pass the URL into the URL constructor to get the same result.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *