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

FunctionSignatureDescription
parseurl.parse(s: string) → objectParse a URL into an object with scheme, host, port, path, rawQuery, query, fragment, user, pass (void on parse failure)
buildurl.build(parts: object) → stringBuild 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
encodeurl.encode(s: string) → stringPercent-encode a string for a query value position
decodeurl.decode(s: string) → stringReverse url.encode (returns the input unchanged if it cannot decode)
encodePathurl.encodePath(s: string) → stringPercent-encode a string for a path segment
parseQueryurl.parseQuery(s: string) → objectParse a query string like "a=1&b=2" into an object; multi-value params become string arrays
buildQueryurl.buildQuery(params: object) → stringEncode 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
Standard library · View as Markdown · llms-full.txt