CKTIS / JavaScript
URL.hash and URL.href: fragment versus full URL
Use `hash` to read or change the fragment and `href` to read or replace the whole URL. The `hash` getter alone cannot distinguish an empty fragment from an absent one.
Version: Current web platform; runtime support varies
Syntax
const url = new URL(input, base); // Omit base for an absolute input.
url.hash; // Fragment string
url.hash = fragment;
url.href; // Full serialized URL
url.href = absoluteUrl;URL.hash/href refers to two instance properties, not methods or static properties. url.hash returns a nonempty fragment with its leading #; it returns "" when the fragment is empty or absent. url.href returns the full serialized URL, including the query if present. A trailing # in href distinguishes an empty fragment from an absent one.
Assign fragment text to url.hash with or without a leading #. Characters such as spaces are percent-encoded as needed, but reading hash does not automatically decode them. url.hash = "" removes the fragment; url.hash = "#" leaves an empty fragment. The fragment is separate from the query: url.searchParams handles query parameters, and the fragment is not automatically sent to the server in an HTTP request.
Assigning to url.href parses the new value and replaces the whole URL on the same object. If parsing fails, it throws TypeError. The setter does not resolve relative references against the current URL; use new URL(relative, base).href with a valid base for that.
Changing a URL object does not navigate, unlike assigning to window.location.href. Before navigating to an untrusted URL, check that its scheme and origin are allowed: successful parsing does not make it safe. URL is a web-platform API, not part of ECMAScript 2024; availability depends on the runtime.
Examples
{
const url = new URL("https://example.com/guide?lang=en");
const show = () => console.log(JSON.stringify([url.hash, url.href]));
url.hash = "quick start";
show();
url.hash = "#";
show();
url.hash = "";
show();
url.href = "https://example.org/start#intro";
show();
}Result
["#quick%20start","https://example.com/guide?lang=en#quick%20start"] ["","https://example.com/guide?lang=en#"] ["","https://example.com/guide?lang=en"] ["#intro","https://example.org/start#intro"]
Each line shows `[hash, href]`. Notice `%20`, the trailing `#` on the second line only, and the full URL replacement on the last line.
Related lessons
- JavaScript · Lesson 30 · Advanced · Version: 4