Decompose an HTTP URL into Components
Problem statement
Parse one valid HTTP or HTTPS URL and return these six components in order:
- scheme, without
://; - host;
- explicit port, or an empty string when no port is written;
- path;
- query, without
?; - fragment, without
#.
URL subset for this exercise
- The scheme is exactly
httporhttps. - The host is nonempty and contains lowercase English letters, digits, dots, or hyphens.
- An optional port follows the host as
:digits. - An optional path begins with
/. If it is absent, return/. - An optional query begins with
?, and an optional fragment begins with#. - The query and fragment may be empty. Delimiter characters do not appear inside their component values.
What the interview report shared
The reported internship team screen asked the candidate to decompose an HTTP URL. The original grammar and returned fields were not preserved.
Function
decomposeHttpUrl(url: String) → String[]Examples
Example 1
url = "https://api.example.com:8443/v1/payments?limit=10#recent"return = ["https","api.example.com","8443","/v1/payments","limit=10","recent"]Every optional component is present. The returned query and fragment omit their leading delimiters.
Example 2
url = "http://example.com?debug=#"return = ["http","example.com","","/","debug=",""]No explicit port or path is written. The query is debug=, and the fragment is present but empty.
Constraints
8 <= url.length <= 2 * 10^5.urlfollows the URL subset stated above.- The explicit port, when present, contains one to five decimal digits.
- For this exercise, preserve component text exactly as written.