Extracting URL Parts

JavaScript provides several built-in methods that can be used to extract different parts of a URL. Here is a tutorial on how to extract the protocol, hostname, pathname, and query parameters of a URL in JavaScript.

To extract the protocol (e.g. "HTTP" or "HTTPS") of a URL, you can use the protocol property of the URL object. For example:

1let url = new URL("https://decode.sh/extracting-url-parts?query=false");
2let protocol = url.protocol;
3console.log(protocol); // "https:"

To extract a URL's hostname (e.g. "decode.sh"), you can use the hostname property of the URL object. For example:

1let url = new URL("https://decode.sh/extracting-url-parts?query=false");
2let hostname = url.hostname;
3console.log(hostname); // "decode.sh"

To extract the pathname (e.g. "/extracting-url-parts") of a URL, you can use the pathname property of the URL object. For example:

1let url = new URL("https://decode.sh/extracting-url-parts?query=false");
2let pathname = url.pathname;
3console.log(pathname); // "/extracting-url-parts"

To extract the query parameters of a URL, you can use the searchParams object of the URL object. This object provides methods for working with the query string of a URL. For example, you can use the get() method to get the value of a specific query parameter.

1let url = new URL("https://decode.sh/extracting-url-parts?query=false");
2let query = url.searchParams.get("query");
3console.log(query); // "false"

To extract the fragment or hash of a URL, you can use the hash property of the URL object.

1let url = new URL(
2  "https://decode.sh/extracting-url-parts?query=false#fragment"
3);
4let fragment = url.hash;
5console.log(fragment); // "#fragment"

Note that the URL object is not supported in some older browsers, so you might need a polyfill or a third-party library such as URL-parse if you need to keep those browsers.