MDN self-hosted library · e01.org
URL / notebook

URL

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
const url = new URL("cats", "http://www.example.com/animals/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/animals/cats"
js
if (URL.canParse("cats", "http://www.example.com/animals/dogs")) {
  const url = new URL("cats", "http://www.example.com/animals/dogs");
  console.log(url.hostname); // "www.example.com"
  console.log(url.pathname); // "/animals/cats"
} else {
  console.log("Invalid URL");
}
js
url.hash = "tabby";
console.log(url.href); // "http://www.example.com/animals/cats#tabby"
js
url.pathname = "démonstration.html";
console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"
js
// https://some.site/?id=123
const parsedUrl = new URL(window.location.href);
console.log(parsedUrl.searchParams.get("id")); // "123"
js
const response = await fetch(
  new URL("http://www.example.com/démonstration.html"),
);