URL

URL parsing, components, and live search parameters.

const url = new URL("https://user:pw@example.com:8080/a?x=1#frag");
url.host;     // "example.com:8080"
url.pathname; // "/a"
url.origin;   // "https://example.com:8080"

new URL(input, base?) throws TypeError on parse failure. URL.parse(input, base?) returns null instead, and URL.canParse(input, base?) returns a boolean.

Components

The mutable components are href, protocol, username, password, host, hostname, port, pathname, search, and hash. origin and searchParams are read-only attributes.

Host names are IDNA-normalized and IPv6 literals retain brackets.

new URL("https://日本.jp/").hostname; // "xn--wgv71a.jp"
new URL("http://[::1]:9000/").host;  // "[::1]:9000"

Most invalid component assignments are ignored. Assigning an invalid href throws TypeError. Default ports serialize as an empty port.

Live search parameters

const url = new URL("https://example.com/?a=1");
const params = url.searchParams;

params.append("b", "2");
url.href; // "https://example.com/?a=1&b=2"

url.search = "?c=3";
params.toString(); // "c=3"

The same URLSearchParams object is returned on every access.

See also