url

Percent-encoding, query-string handling, and full URL parsing/building.

import url

Component encoding

url_encode_component(text) → string

Percent-encode a single component, escaping reserved characters.

url_encode_component("a b&c")
-- Output: "a%20b%26c"
url_decode_component(text) → string

Decode a percent-encoded component (and turn + into a space).

url_decode_component("a%20b%26c")
-- Output: "a b&c"

Query utilities

build_query(pairs) → string

Build a query string from a list of [key, value] pairs, encoding each part.

build_query([["a", "1"], ["name", "bern lang"]])
-- Output: "a=1&name=bern%20lang"
parse_query(query) → object

Parse a query string into an object of decoded keys and values.

params = parse_query("a=1&name=bern%20lang")
params["name"]
-- Output: "bern lang"

Full URL operations

parse_url(url_text) → object

Parse a URL into scheme, host, port, path, query, and fragment. Default ports are filled in for http (80) and https (443).

parsed = parse_url("http://example.com:8080/docs/api?x=1#top")
parsed["host"]
-- Output: "example.com"
parsed["port"]
-- Output: 8080
parsed["path"]
-- Output: "/docs/api"
build_url(scheme, host, port, path, query, fragment) → string

Assemble a URL from its components. A port equal to the scheme's default is omitted.

build_url("https", "example.com", 443, "/hello", "a=1", "frag")
-- Output: "https://example.com/hello?a=1#frag"

Putting it together

The pieces combine for a full round trip: parse a URL, edit its query, and rebuild it. Here we add a parameter to an existing link:

Adding a query parameter to a URL

import url

original = "https://search.example.com/?q=bern"

u = parse_url(original)
params = parse_query(u["query"])
params["page"] = "2"

-- rebuild the query from the (now larger) object
new_query = build_query([["q", params["q"]], ["page", params["page"]]])

build_url(u["scheme"], u["host"], u["port"], u["path"], new_query, "")
-- Output: "https://search.example.com/?q=bern&page=2"

And encoding user input safely before putting it in a link:

Safely linking a search term

import url

term = "bern lang & friends"
"https://example.com/?q=" + url_encode_component(term)
-- Output: "https://example.com/?q=bern%20lang%20%26%20friends"