Post cover

How to Parse URL in JavaScript: hostname, pathname, query, hash

A Uniform Resource Locator, abbreviated URL, is a reference to a web resource (web page, image, file). The URL specifies the resource location and a mechanism to retrieve the resource (http, ftp, mailto).

For example, here's the URL of this blog post:

Often you need to access specific components of an URL. These might be the hostname (e.g., or pathname (e.g. /parse-url-javascript).

A convinient parser to access components of an URL is the URL() constructor.

In this post, I'm going to show you the structure of an URL and its main components.

Then, I'm going to describe how to use the URL() constructor to easily pick components of an URL like hostname, pathname, query, or hash.

1. URL structure

An image worth a thousand words. Without much textual description, in the following image you can find the main components of an URL:

URL() constructor components in JavaScript

2. URL() constructor

The URL() is a constuctor function that enables the parsing of components of an URL:

const url = new URL(relativeOrAbsolute [, absoluteBase]);

relativeOrAbsolute argument can be either an absolute or relative URL. If the first argument is relative, then the second argument absoluteBase is obligatory and must be an absolute URL being the base for the first argument.

For example, let's initialize URL() with an absolute URL:

const url = new URL('');
url.href; // => ''

or combine a relative and absolute URLs:

const url = new URL('/path/index.html', '');
url.href; // => ''

The href property of the URL() instance returns the entire URL string.

After creating an URL() instance, you can access any URL component presented in the previous picture. For reference, here's the URL() instance interface:

interface URL {
href: USVString;
protocol: USVString;
username: USVString;
password: USVString;
host: USVString;
hostname: USVString;
port: USVString;
pathname: USVString;
search: USVString;
hash: USVString;
readonly origin: USVString;
readonly searchParams: URLSearchParams;
toJSON(): USVString;

where USVString type maps to a string when returned in JavaScript.

3. Query string property accesses the query string of the URL prefixed with ?:

const url = new URL(
);; // => '?message=hello&who=world'

If the query string is missing, evaluates to an empty string '':

const url1 = new URL('');
const url2 = new URL('');; // => ''; // => ''

3.1 Parsing query string

More handy than accessing the raw query string is to access the query parameters.

An easy way to pick query parameters gives url.searchParams property. This property holds an instance of URLSearchParams.

URLSearchParams object provides lots of methods (like get(param), has(param)) to access the query string parameters.

Let's look at an example:

const url = new URL(
url.searchParams.get('message'); // => 'hello'
url.searchParams.get('missing'); // => null

url.searchParams.get('message') returns the value of message query parameter — 'hello'.

However accessing a non-existing parameter url.searchParams.get('missing') evaluates to null.

4. hostname

url.hostname property holds the hostname of the URL:

const url = new URL('');
url.hostname; // => ''

5. pathname

url.pathname property accesses the pathname of the URL:

const url = new URL('');
url.pathname; // => '/path/index.html'

If the URL doesn't have a path, the url.pathname property returns a slash character /:

const url = new URL('');
url.pathname; // => '/'

6. hash

Finally, the hash can be accessed using url.hash property:

const url = new URL('');
url.hash; // => '#bottom'

When the hash in the URL is missing, url.hash evaluates to an empty string '':

const url = new URL('');
url.hash; // => ''

7. URL validation

When new URL() constructor creates an instance, as a side effect, it also validates the URL for correctness. If the URL value is invalid, a TypeError is thrown.

For example, http :// is an invalid URL because of the space character after http.

Let's use this invalid URL to initialize the parser:

try {
const url = new URL('http ://');
} catch (error) {
error; // => TypeError, "Failed to construct URL: Invalid URL"

Because 'http ://' is an invalid URL, as expected, new URL('http ://') throws a TypeError.

8. URL manipulation

Aside from accessing URL components, the properties like search, hostname, pathname, hash are writeable — thus you can manipulate the URL.

For example, let's modify the hostname of an existing URL from to

const url = new URL('');
url.href; // => ''
url.hostname = '';
url.href; // => ''

Note that only origin and searchParams properties of the URL() instance are readonly. All the other one are writable and modify the URL when you change them.

9. Summary

The URL() constructor is handy to parse (and validate) URLs in JavaScript.

new URL(relativeOrAbsolute [, absoluteBase]) accepts as first argument an absolute or relative URL. When the first argument is relative, you have to indicate the second argument as an abolsute URL that serves the base for the first argument.

After creating the URL() instance, you can easily access the most common URL components like:

  • for raw query string
  • url.searchParams for an instance of URLSearchParams to pick query string parameters
  • url.hostname to access the hostname
  • url.pathname to read the pathname
  • url.hash to determine the hash value

Regarding browser support, URL constructor is available in modern browsers. It is not, however, available in Internet Explorer.

What is your favorite tool to parse URLs in JavaScript?

Like the post? Please share!

Quality posts into your inbox

I regularly publish posts containing:

  • Important JavaScript concepts explained in simple words
  • Overview of new JavaScript features
  • How to use TypeScript and typing
  • Software design and good coding practices

Subscribe to my newsletter to get them right into your inbox.

Join 5681 other subscribers.
Dmitri Pavlutin

About Dmitri Pavlutin

Tech writer and coach. My daily routine consists of (but not limited to) drinking coffee, coding, writing, coaching, overcoming boredom 😉.
Email addressTwitter profileFacebook pageLinkedIn profile