URL interface is used to parse, construct, normalize, and encode URLs. It works by providing properties which allow you to easily read and modify the components of a URL.
You normally create a new
URL object by specifying the URL as a string when calling its constructor, or by providing a relative URL and a base URL. You can then easily read the parsed components of the URL or make changes to the URL.
If a browser doesn't yet support the
URL() constructor, you can access a URL object using the
URL property. Be sure to check to see if any of your target browsers require this to be prefixed.
The constructor takes a
url parameter, and an optional
base parameter to use as a base if the
url parameter is a relative URL:
const url = new URL("../cats", "http://www.example.com/dogs");
URL properties can be set to construct the URL:
url.hash = "tabby";
URLs are encoded according to the rules found in RFC 3986. For instance:
url.pathname = "démonstration.html";
URLSearchParams interface can be used to build and manipulate the URL query string.
To get the search params from the current window's URL, you can do this:
const parsedUrl = new URL(window.location.href);
toString() method of
URL just returns the value of the
href property, so the constructor can be used to normalize and encode a URL directly.
const response = await fetch(