url
Parse URLs into navigable objects, rebuild them from parts, and percent-encode or decode strings and query parameters. Import it with import url.
Functions
| Function | Signature | Description |
|---|---|---|
parse | url.parse(s: string) → object | Parse a URL into an object with scheme, host, port, path, rawQuery, query, fragment, user, pass (void on parse failure) |
build | url.build(parts: object) → string | Build a URL string from an object with the same shape as parse; missing fields are omitted, query may be a raw string or an object |
encode | url.encode(s: string) → string | Percent-encode a string for a query value position |
decode | url.decode(s: string) → string | Reverse url.encode (returns the input unchanged if it cannot decode) |
encodePath | url.encodePath(s: string) → string | Percent-encode a string for a path segment |
parseQuery | url.parseQuery(s: string) → object | Parse a query string like "a=1&b=2" into an object; multi-value params become string arrays |
buildQuery | url.buildQuery(params: object) → string | Encode an object into a query string with keys sorted for deterministic output |
In a parsed query/parseQuery object, single-value params are string fields and repeated params become string arrays. When building, array fields emit repeated params (foo=a&foo=b) and void fields are skipped.
Example
import url
// inspect URL parts
let u = url.parse("https://example.com:8443/search?q=hello+world&tag=a&tag=b")
print(u.host) // example.com
print(u.port) // 8443
print(u.query.q) // hello world
// rebuild a URL from parts
let link = url.build({
scheme: "https",
host: "api.example.com",
path: "/v1/items",
query: { page: "2", limit: "50" },
})
print(link) // https://api.example.com/v1/items?limit=50&page=2
// encode a single value
print(url.encode("a b&c")) // a+b%26c