URL
URL parses, manipulates, and normalizes URLs; URLSearchParams is a
map-like view of a URL query string — the part after ?. Both handle
the percent-encoding rules for you.
new URL(url, base)parses a URL; relative URLs requirebase.- Component getters/setters:
href,protocol,username,password,hostname,port,pathname,search,hash,origin(read-only). url.searchParamsis a liveURLSearchParamsview of the query.new URLSearchParams(init)creates params from a query string ("a=1&b=2"), an object of key/value pairs, or another instance.- Params support
get/getAll/has/append/set/delete/sort, iteration (entries(),keys(),values(),forEach()), andtoString(). url.toString()/url.toJSON()return the serialized URL.
Usage#
const url = new URL("https://api.example.com/v1/users?limit=10&page=2");
url.hostname; // "api.example.com"
url.pathname; // "/v1/users"
url.searchParams.get("limit"); // "10"
Resolving relative URLs:
new URL("/images/logo.png", "https://example.com/products").href;
// "https://example.com/images/logo.png"
Building and editing query strings:
const params = new URLSearchParams({ q: "cron jobs", limit: "25" });
params.append("fields", "id");
params.append("fields", "name");
params.get("q"); // "cron jobs"
params.getAll("fields"); // ["id", "name"]
params.toString(); // "q=cron+jobs&limit=25&fields=id&fields=name"
const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "status checks");
fetch(url); // https://api.example.com/search?q=status+checks
Invalid URLs throw:
try {
new URL("not a url");
} catch (err) {
console.log(err instanceof TypeError); // true
}