URLs (Uniform Resource Locators) are the backbone of the internet. They lead us to the website and other resources that exist on the internet. A URL is composed of different segments that for the most part go above our heads. But sometimes is necessary to understand when developing an application.
The URL
For a simplistic view, the url is composed of 5 parts:
- The protocol: 'https:', 'wss:', 'http:', etc
- The subdomain: 'www', 'blog', 'admin',etc
- The second-level domain (SLD): 'google', 'npdt', 'youtube', etc
- The top-level domain (TLD): '.com', '.eu', '.dev', etc
- The path: '/resource/1', '/about', '/hello/world'
This elements can pretty much cover all of everyday navigation. The protocol tells the browser or another client how to connect to the website. The subdomain is a segment that subdivides the domain that can be optional or be pretty much whatever text you want (most common one is www). The second level domain is the name of the website. The top level domain or domain extension is used to identify between 'domains' in the top level of the hierarchical Domain Name System of the Internet. And lastly the path is used for finding resources inside the site, similar to a file browser.
The URL in Javascript
Part of the WEB APIs include the URL object. To create one we use its constructor with the URL as a string or alternative we can use another variation of its constructor that takes the relative URL and the base. If the URL is incorrect in the context of format, it will throw a TypeError
.
const url = new URL("https://google.com");
const otherUrl = new URL("/en/blog","https://npdt.dev");
The URL object has several properties that we as a developer might need to use in our applications. Those that I deemed most important inside an application are the following:
hostname
: domain name of the URL.host
: hostname, and then the port if it is nonempty.href
: the full url.pathname
: the relative location of the resource.searchParams
: the url search params.
The following graphic shows the output of several of the URL properties in a more complex example.
Conclusion
It's in important as a developer to understand the building blocks of the web, this time it was the URL. Personally, I always forget which part is what in the URL object in javascript, but with this cheatsheet I can quickly lookup what part of the URL I might need to use in an application.