Chapter 3. URLs and Routing
Introduction
Most web pages and applications deal with URLs in some way. This could be an action like crafting a link with certain query parameters, or URL-based routing in a single-page application (SPA).
A URL is just a string that complies with some syntax rules as defined in RFC 3986, “Uniform Resource Identifier (URI): Generic Syntax”. There are several component parts of a URL that you may need to parse or manipulate. Doing so with techniques like regular expressions or string concatenation isn’t always reliable.
Today, browsers support the URL API. This API provides a URL
constructor that can create, derive, and manipulate URLs. This API was somewhat limited at first, but later updates added utilities like the URLSearchParams
interface that simplified building and reading query strings.
Parts of a URL
When you call the URL
constructor with a string representing a valid URL, the resulting object contains properties representing the URL’s different component parts. Figure 3-1 shows the most commonly used of these:
protocol
(1)-
For web URLs, this is typically
http:
orhttps:
(note that the colon is included, but not the slashes). Other protocols are possible such asfile:
(for a local file not hosted on a server) orftp:
(a resource on an FTP server). hostname
(2)-
The domain or host name (
example.com
). pathname
(3)-
The path of the resource relative to the root, with leading slash (
/admin/login
). search
(4)-
Any query parameters. The
?
Get Web API Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.