Resolve relative URLs
Resolve route or asset references against a known origin or document URL.
JavaScript · Class
The URL interface parses, constructs, normalizes, and encodes URLs. It exposes URL components for inspection and modification, and can resolve relative references against a base URL.
The URL interface parses and builds URL values while exposing their components as readable and writable properties. Create one with an absolute URL or resolve a relative reference against a base URL; use URLSearchParams through searchParams to manipulate its query.
new URL(url)
new URL(url, base)| Name | Type | Description |
|---|---|---|
url | string or stringifiable object | An absolute URL string or a relative reference to resolve against base. |
base | string or stringifiable object | The URL used to resolve a relative url; optional when url is absolute. |
A URL object representing the resolved and parsed URL.
new URL() and an absolute URL string.URL.canParse() performs a non-throwing validity test and returns a boolean.URL.parse() returns a URL object or null when the definition is invalid.URLSearchParams through searchParams to work with query parameters.const url = new URL("/docs", "https://developer.mozilla.org/en-US/");
url.searchParams.set("q", "URL");
console.log(url.href);Constructs an absolute URL from a relative path, adds a query parameter, and prints the serialized result.
Resolve route or asset references against a known origin or document URL.
Inspect or update protocol, host, path, fragment, and query components.
Validate URL input before attempting to use it.
Build and update query strings with structured parameter operations.
The constructor accepts an absolute URL, or a relative reference together with a base URL. It returns a URL object whose components can be inspected and changed.
Follow-up: What happens if the input is relative and no base is supplied? Construction throws TypeError because the reference cannot be resolved.
Use URL.canParse(url, base) when a boolean validity check is sufficient. Unlike construction, this static method reports whether the URL definition is parsable and valid.
Follow-up: How can invalid input be represented without an exception? URL.parse(url, base) returns a URL object for valid input and null for invalid input.
The searchParams property exposes URLSearchParams for building and manipulating the query string. Methods such as set() update the URL's query parameters.
Follow-up: How does direct query-string assignment differ? The search property represents the query string and setting it applies URL encoding rules.
URLSearchParamsURL.canParse()URL.parse()URL.hrefURL.searchParams