Codectionary / Developer documentation / JavaScript

URL and URLSearchParams

The URL object parses and constructs URLs, giving structured access to their parts (protocol, host, pathname, etc.) without manual string manipulation. URLSearchParams specifically handles query string parameters - reading, adding, and removing them correctly, including proper encoding.

Syntax

new URL(urlString)
new URLSearchParams(queryString)

Examples

Parsing a URL

Breaking a URL into its structured parts.

const url = new URL("https://example.com:8080/products?category=shoes&sort=price#reviews");

console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.port);     // "8080"
console.log(url.pathname); // "/products"
console.log(url.search);   // "?category=shoes&sort=price"
console.log(url.hash);     // "#reviews"

Reading and Modifying Query Parameters

Working with query strings without manual parsing or string concatenation.

const url = new URL("https://example.com/search?q=javascript&page=1");

console.log(url.searchParams.get("q"));    // "javascript"
console.log(url.searchParams.get("page")); // "1"

url.searchParams.set("page", "2");
url.searchParams.append("sort", "recent");

console.log(url.toString());
// "https://example.com/search?q=javascript&page=2&sort=recent"

Building Query Strings from Scratch

Using URLSearchParams standalone, without a full URL.

const params = new URLSearchParams();
params.set("name", "Alice Smith"); // spaces are correctly encoded
params.set("role", "admin");

console.log(params.toString()); // "name=Alice+Smith&role=admin"

fetch(`/api/users?${params.toString()}`);

Best practices

  • Use the URL and URLSearchParams objects instead of manually splitting and concatenating query strings - they correctly handle encoding edge cases
  • Use searchParams.set() to overwrite a parameter and searchParams.append() to add an additional value for the same key
  • Always construct URLs this way when building requests with dynamic query parameters, to avoid manual encoding bugs
  • Remember getAll() (not get()) is needed to retrieve multiple values for the same parameter key

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading