How to Get Parts of a URL in JavaScript
Parsing a URL to extract its individual components—such as the protocol, hostname, port, or query parameters—is a fundamental task in web development. You might need to check the domain, read a query parameter, or build a new URL based on the current one.
This guide will teach you the modern, standard method for parsing URLs using the powerful, built-in URL object. You will learn how to easily access every part of a URL in a structured and reliable way.
The Modern Method (Recommended): The URL Object
The URL interface is the modern, robust, and recommended way to parse and work with URLs. It provides a standardized object model for deconstructing a URL string into its constituent parts.
The logic:
- You create a new
URLobject by passing a full URL string to its constructor. The resulting object has properties that give you direct access to each part of the URL.
For example, we have a complex URL string and need to extract specific parts from it.
// Problem: How to get the hostname, pathname, and search params from this URL?
const myUrlString = 'https://www.example.com:8080/path/to/page?id=123&user=alice#section-2';
Solution:
const myUrl = new URL('https://www.example.com:8080/path/to/page?id=123&user=alice#section-2');
console.log('Hostname:', myUrl.hostname); // Output: "www.example.com"
console.log('Pathname:', myUrl.pathname); // Output: "/path/to/page"
console.log('Search:', myUrl.search); // Output: "?id=123&user=alice"
This is the cleanest and most reliable way to parse any URL string.
How to Use the URL Object
You can create a URL object from any valid URL string. A very common use case is to parse the current page's URL.
// Get the current page's full URL
const currentUrlString = window.location.href;
// Create a URL object from it
const currentUrl = new URL(currentUrlString);
console.log('Current Protocol:', currentUrl.protocol);
console.log('Current Host:', currentUrl.host);
A List of Key URL Properties
Once you have a URL object, you can access all of its components with these simple properties:
| Property | Description | Example from https://u:p@www.e.com:80/p?q=1#h |
|---|---|---|
href | The entire URL string. | "https://user:pass@www.example.com:8080/path?query=1#hash" |
protocol | The protocol scheme, including the trailing colon (:). | "https:" |
hostname | The domain name. | "www.example.com" |
port | The port number as a string. | "8080" |
host | The hostname and port combined. | "www.example.com:8080" |
origin | The protocol, hostname, and port combined. | "https://www.example.com:8080" |
pathname | The path, including the leading /. | "/path" |
search | The entire query string, including the leading ?. | "?query=1" |
searchParams | A URLSearchParams object for easily accessing query parameters. | URLSearchParams object |
hash | The fragment identifier, including the leading #. | "#hash" |
Using searchParams
The searchParams property is particularly useful as it provides a set of methods for working with query parameters.
const url = new URL('https://example.com?id=123&user=alice');
const params = url.searchParams;
console.log(params.get('id')); // Output: "123"
console.log(params.has('user')); // Output: true
The Legacy Method: window.location
Before the URL constructor was widely available, developers accessed the parts of the current page's URL via the global window.location object. It has properties with the same names as the URL object (e.g., window.location.hostname, window.location.pathname).
Limitation: The window.location object can only be used to parse the current page's URL. It cannot be used to parse an arbitrary URL string. This is why the URL object is the superior and more flexible tool.
Conclusion
Parsing URLs in modern JavaScript is a simple and reliable task thanks to the built-in URL object.
- The
new URL(urlString)constructor is the modern and recommended best practice for parsing any URL string. - The resulting
URLobject provides clean, readable properties for accessing every component of the URL, from theprotocolto thehash. - The
searchParamsproperty is the standard way to work with query string parameters. - Avoid relying on the older
window.locationobject unless you specifically only need to parse the current page's URL.