CKTIS / JavaScript
`URL.origin`, `URL.pathname`, and `URL.search`
Distinguish a parsed URL’s origin, path, and query, and read individual query parameters without splitting the address by hand.
Version: Current web platform; runtime support varies
Syntax
const url = new URL(input);
const resolved = new URL(input, base);
url.origin;
url.pathname;
url.search;
url.pathname = "/catalog";
url.search = "page=2";URL.origin/pathname/search refers to three properties on a URL instance, not methods. URL is a web platform API, not part of ECMAScript 2024, so check that your runtime provides it. Use new URL(input) for an absolute URL and supply a suitable base with new URL(input, base) for a relative reference. An invalid supplied base or a parse failure throws TypeError. Changing the URL object does not navigate.
origin is read-only. For HTTP(S), it contains the scheme and hostname, plus the port if it is non-default. It excludes credentials, path, query, and fragment. An opaque origin, as with a data: URL, serializes to the string "null", not the value null. Two such strings do not establish a shared origin. The result for file: depends on the implementation.
pathname is the serialized path, without the query or fragment. For HTTP(S), it starts with /, and the root path is /. Percent escapes such as %20 are not automatically decoded. You can assign a new HTTP(S) path. Other schemes can have an opaque path with no leading /.
search returns the query with its leading ?, without the fragment and without decoding percent escapes. It returns "" when the query is absent or empty, including for a bare ?. Assign a new query with or without the leading ?; assign "" to remove it.
Use url.searchParams.get("q") to read a decoded parameter value. Mutating searchParams updates the same URL object and can change how existing values are serialized: a space written as %20 can become +. Use href to read the full URL, including the fragment.
Examples
{
const url = new URL("/catalog/./tea%20sets?q=green%20tea#reviews", "https://shop.example:443/");
console.log(url.origin);
console.log(url.pathname);
console.log(url.search);
console.log(url.searchParams.get("q"));
url.searchParams.set("page", "2");
console.log(url.href);
}Result
https://shop.example /catalog/tea%20sets ?q=green%20tea green tea https://shop.example/catalog/tea%20sets?q=green+tea&page=2#reviews
Normalization drops the default port `443` and the `.` path segment. `search` keeps `%20`, `get("q")` returns a value with a space, and adding `page=2` changes that space’s representation in the query to `+`.
Related lessons
- JavaScript · Lesson 38 · Advanced · Version: 4