CodeStride
Foundations · build it

Parse a URL

EasyFree

Before a browser can send a request, it pulls the web address apart. The host goes to DNS, and the port says where to connect. The path and query travel in the HTTP request.

You get a web address, url, such as "https://shop.example.com:8080/cart/items?id=42&size=m". Split it into its parts and return a dictionary (an object in JavaScript) with five keys.

scheme is the text before ://: "http" or "https".

host is the name after ://, up to a :, / or ?.

port is the number after the host's :. When there's none, it's 443 for https and 80 for http.

path starts at the first / after the host and runs up to the ?. When there's none, it's "/".

query is a dictionary of each key to its value, from the key=value pairs after the ?, split by &. Values stay as text. When there's no ?, it's an empty dictionary.

Split it yourself, without the language's URL tools.

Example 1

Input
url = 'https://shop.example.com:8080/cart/items?id=42&size=m'
Output
{'scheme': 'https', 'host': 'shop.example.com', 'port': 8080, 'path': '/cart/items', 'query': {'id': '42', 'size': 'm'}}

Every part is there. The port is 8080 because it's written out, and 42 stays the text "42".

Example 2

Input
url = 'http://example.com'
Output
{'scheme': 'http', 'host': 'example.com', 'port': 80, 'path': '/', 'query': {}}

Only the scheme and host are written, so the port, path and query take their defaults.

Example 3

Input
url = 'https://news.example.org/search?q=cats'
Output
{'scheme': 'https', 'host': 'news.example.org', 'port': 443, 'path': '/search', 'query': {'q': 'cats'}}

There's no port, and https means 443.

Constraints

  • url starts with http:// or https://, and 1 <= length of url <= 2,000
  • The host has letters, digits, dots and hyphens; a written port is 1 to 65,535
  • After a ?, there's at least one key=value pair; each key appears once, and keys and values have no &, = or ?
  • There's no username, password or #fragment

Build it in your browser

Write it in Python or JavaScript, run it on the examples, then submit it against hidden tests, with hints and worked solutions when you need them.