Percent-encoding, query-string handling, and full URL parsing/building.
import url
Percent-encode a single component, escaping reserved characters.
url_encode_component("a b&c")
-- Output: "a%20b%26c"
Decode a percent-encoded component (and turn + into a space).
url_decode_component("a%20b%26c")
-- Output: "a b&c"
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 a query string into an object of decoded keys and values.
params = parse_query("a=1&name=bern%20lang")
params["name"]
-- Output: "bern lang"
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"
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"
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:
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:
import url term = "bern lang & friends" "https://example.com/?q=" + url_encode_component(term) -- Output: "https://example.com/?q=bern%20lang%20%26%20friends"