URL - patrickcole/learning GitHub Wiki

URL Object

// Absolute paths:
const absURL = new URL(`https://www.example.com/articles/URL.md`);

// Relative path:
const relativeURL = new URL(`/articles/URL.md`, `https://www.example.com`);

// Using absURL to create new URL:
const articlesURL = new URL(`/contact`, absURL);
console.log(articlesURL.toString());
// => https://www.example.com/contact

Useful for looking at properties of a URL:

const url = new URL(`https://www.example.com/articles/url.md#section1`);

console.log(url.protocol);
// => "https:"
console.log(url.host);
// => "example.com"
console.log(url.pathname);
// => "/articles/url.md"
console.log(url.hash);
// => "#section1"
console.log(url.origin);
// => "https://www.example.com"
  • A good use case for using the URL object is fetch

Sources