JavaScript URL API
Learn the JavaScript URL API: parse a URL into its components, edit query strings with URLSearchParams, resolve relative URLs, and avoid common pitfalls.
Introduction to JavaScript URL Objects
JavaScript provides a powerful built-in URL interface to construct, parse, and manipulate URLs. Instead of slicing strings with regular expressions or manual split() calls — which break on edge cases like ports, encoded characters, and missing components — the URL object parses an address into structured, individually addressable parts.
The URL interface is available natively in browsers and in Node.js (it is a global, no require needed). This guide covers how to create and parse URLs, read and modify each component, work with query strings through URLSearchParams, and handle common real-world tasks such as building API requests and tracking links.
Creating and Parsing URLs with JavaScript
Basic URL Creation
To create a URL, pass the address string to the URL constructor. If the string is not a valid absolute URL, the constructor throws a TypeError:
const url = new URL("https://www.w3docs.com");Parsing URL Components
Once a URL object is created, you can read any part of it through a dedicated property:
The full set of components for a URL like https://user:[email protected]:8080/path?q=1#top is:
| Property | Example value | Description |
|---|---|---|
href | the whole URL | The complete URL as a string. |
protocol | https: | The scheme, including the trailing colon. |
hostname | www.w3docs.com | The domain without the port. |
port | 8080 | The port, or "" if the default for the protocol. |
host | www.w3docs.com:8080 | hostname plus port. |
origin | https://www.w3docs.com:8080 | Protocol + host (read-only). |
pathname | /path | The path after the host. |
search | ?q=1 | The query string, including the leading ?. |
searchParams | a URLSearchParams object | Parsed query parameters (read-only object, editable contents). |
hash | #top | The fragment, including the leading #. |
Validating a URL Before Parsing
Because the constructor throws on invalid input, validate untrusted strings first. The static URL.canParse() method returns a boolean without throwing:
Manipulating URL Objects
Working with the Query String via URLSearchParams
Every URL exposes a searchParams property — a live URLSearchParams object whose changes write straight back to the URL. This is the preferred way to edit a query string, because it handles encoding for you. The example below uses a separate URLSearchParams to show how the pieces fit together:
In practice you usually skip the intermediate object and edit url.searchParams directly — it mutates the URL in place:
Repeated Keys and Iteration
Query strings can contain the same key more than once (for example ?tag=js&tag=web). get() returns only the first match, while getAll() returns every value. You can also loop over all pairs with for...of:
Explanation
- Initialization:
- The
URLobject is created with a base URL that already includes a query parameter (initial=123).
- The
- URLSearchParams Object:
URLSearchParamsis initialized withurl.search, which contains the query string from the URL.
- Add a Parameter:
- The
.set()method is used to add a new parameter (key=value) to the query string. If the key already exists, its value is updated; if it doesn't, the key-value pair is added.
- The
- Read a Parameter:
- The
.get()method retrieves the value of the parameter specified by the key (key), which is then logged to the console.
- The
- Remove a Parameter:
- The
.delete()method removes the parameter specified by the key (initial). This is used to demonstrate how to remove a parameter from the query string.
- The
- Update URL Search:
- After modifying the parameters, the URL's
searchproperty is updated with the string representation of theURLSearchParamsobject.
- After modifying the parameters, the URL's
- Output:
- Finally, the modified URL is logged to the console, showing the effect of the operations.
Modifying Path and Hash
Here’s a JavaScript snippet that shows how to modify the pathname and hash of a URL:
Explanation
- URL Object Initialization:
- The
URLobject is initially created from a string representing a complete URL. This URL includes a pathname, query string, and hash fragment.
- The
- Modifying the Pathname:
- The
pathnameproperty of the URL object is set to a new path (/path/to/resource). This property specifies the path or route on the server.
- The
- Modifying the Hash:
- The
hashproperty is updated to"section". In URLs, the hash represents a bookmark within the page, often used to scroll to a specific section.
- The
- Logging Changes:
- The original URL is logged before modifications to show the starting state.
- After modifications, the new state of the URL is logged to demonstrate the effects of changing the
pathnameandhash.
Advanced Usage of URL Objects
Handling Relative URLs
The URL object can also resolve relative URLs against a base URL, which is particularly useful for web applications dealing with dynamic links:
Working with URL Encoding
When dealing with URLs that include characters that need encoding, the URL object automatically handles these, ensuring that the URLs are valid:
For handling local files or blobs, URL.createObjectURL() generates a temporary URL string that references the object in memory, which is useful for previewing images or downloading files directly from JavaScript.
Practical Examples of URL Manipulation
Tracking Campaign URLs
You can use URL objects to effectively manage campaign URLs, which are often used in digital marketing to track the performance of various marketing efforts:
Integrating with Web APIs
URL objects pair naturally with the Fetch API: you can pass a URL instance directly to fetch(), and searchParams guarantees the query string is correctly encoded. After the request resolves, you typically parse the response with JSON methods:
Modern alternative (async/await):
async function fetchPosts() {
const apiUrl = new URL("https://jsonplaceholder.typicode.com/posts");
apiUrl.searchParams.set("userId", "1");
const response = await fetch(apiUrl);
const data = await response.json();
console.log(data[0]); // Outputs the first post by user with userId 1
}Common Pitfalls
- The constructor throws on invalid input.
new URL("example.com")fails because it has no protocol. Either provide a full absolute URL, pass a base URL as the second argument, or guard withURL.canParse(). - Relative strings need a base.
new URL("/about")throws on its own;new URL("/about", "https://www.w3docs.com")resolves correctly. originis read-only. You cannot assign tourl.origin. Changeprotocol,hostname, orportindividually instead.get()returns only the first value. For keys that can repeat, usegetAll().- Normalization is automatic. Reading
hrefmay add a trailing slash (https://w3docs.combecomeshttps://w3docs.com/) and percent-encode reserved characters. Compare parsed URLs, not raw strings, when checking for equality. searchParamsorder is insertion order. Useparams.sort()if you need a canonical, stable query string for caching or signing.
Conclusion
The JavaScript URL object is a robust tool for handling all aspects of URL manipulation and analysis. By mastering its properties and methods, developers can streamline their web application's interaction with URLs, enhancing both functionality and user experience. Whether you're managing complex URL structures, integrating with APIs, or tracking marketing campaigns, the URL object offers a reliable and efficient way to work with web addresses in JavaScript.