Skip to content

URL API

In one line

The URL API provides a built-in URL object for parsing, reading, and modifying the components of a URL.

In simple words

The URL API gives you a URL class that parses a URL string into its components — protocol, host, pathname, search params, hash — as readable and writable properties. Instead of fragile string splitting and regex, you work with a structured object and serialize it back to a string when done.

You create a URL with new URL(string) (or new URL(path, base) for relative URLs). Properties like .protocol, .hostname, .port, .pathname, .hash, and .searchParams let you inspect and change each part. The searchParams property is a URLSearchParams object with get, set, append, delete, and has methods for query string manipulation.

This API is the correct way to handle URLs in modern JavaScript. It handles edge cases (encoding, default ports, relative resolution) that hand-rolled string manipulation gets wrong. It is available in browsers and Node.js.

Example

javascript
const url = new URL("https://example.com/users?role=admin&page=2#section");
console.log(url.protocol); // "https:"
console.log(url.hostname);  // "example.com"
console.log(url.pathname);  // "/users"
console.log(url.searchParams.get("page")); // "2"

url.searchParams.set("page", "3");
console.log(url.toString()); // "https://example.com/users?role=admin&page=3#section"

The URL object exposes each part as a property. searchParams lets you read and modify query strings; toString serializes it back.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary