Manual regular expressions and naive split('/') helpers frequently break when confronted with basic-auth credentials, explicit ports, percent-encoded slashes (%2F), multi-part public suffixes like .co.uk, or question marks embedded inside hash fragments. A specification-aware parser scans delimiters in strict syntactic order before decoding individual components.
Consider a complex webhook delivery URL containing credentials, a multi-level subdomain, a non-default TLS port, an encoded path segment, query parameters, and a fragment anchor:
https://deploy:tok_9f8a@staging.api.example.co.uk:8443/v2/orgs/acme%20corp/webhooks?event=push&active=true#delivery-log
Decomposing this URI yields discrete, independently editable properties:
{
"href": "https://deploy:tok_9f8a@staging.api.example.co.uk:8443/v2/orgs/acme%20corp/webhooks?event=push&active=true#delivery-log",
"protocol": "https:",
"scheme": "https",
"username": "deploy",
"password": "tok_9f8a",
"origin": "https://staging.api.example.co.uk:8443",
"host": "staging.api.example.co.uk:8443",
"hostname": "staging.api.example.co.uk",
"subdomain": "staging.api",
"domain": "example.co.uk",
"tld": "co.uk",
"port": "8443",
"pathname": "/v2/orgs/acme%20corp/webhooks",
"pathSegments": ["v2", "orgs", "acme corp", "webhooks"],
"search": "?event=push&active=true",
"queryParams": {
"event": "push",
"active": "true"
},
"hash": "#delivery-log"
}
Mutating Components Without Corrupting Escapes
When debugging across environments, you often need to point a captured production or staging callback URL at a local service while preserving exact path encoding and signed query payloads. Changing scheme to http, hostname to localhost, port to 3000, and clearing username/password cleanly reconstructs:
http://localhost:3000/v2/orgs/acme%20corp/webhooks?event=push&active=true#delivery-log
Notice that the third path segment (acme corp) automatically retains its %20 percent-encoding inside pathname, preventing whitespace truncation in HTTP request lines or Markdown logs.