Reference · Web

url_encode

signature
url_encode(any) -> str

What it does

The value's text written for a URL: every byte but letters, digits and -_.~ becomes %XX. A map gives a query string, a=1&b=x%20y, each key and value encoded, leaving out keys whose value is null. It is encodeURIComponent, except that !'()* are encoded too; the browser's url_encode gives the same.

Examples

print(url_encode("a b"))print(url_encode("a&b=c/d?e#f"))print(url_encode({ q: "a b", page: 2 }))print(`/search?${url_encode({ q: "tea & cake" })}`)
output
a%20ba%26b%3Dc%2Fd%3Fe%23fq=a%20b&page=2/search?q=tea%20%26%20cake

Edge cases

print(url_encode("a+b c"), url_encode("héllo"))print(url_encode("!'()*"), url_encode("-_.~"))print(url_encode({ q: "x", skip: null, n: 0, t: false, e: "" }))print(url_encode({ "a b": "c&d" }), url_encode({}) == "")print(url_encode([1, 2]), url_encode(null))
output
a%2Bb%20c h%C3%A9llo%21%27%28%29%2A -_.~q=x&n=0&t=false&e=a%20b=c%26d true%5B1%2C%202%5D null

Errors

url_encode never fails: a number, a boolean or a decimal is its text. An error value given, or one among a map's values, is given back rather than put in the URL as its text.

print(url_encode(42), url_encode(dec("1.50")), url_encode(true))print(url_encode(err("no page")), url_encode({ q: "x", page: int("two") }))
output
42 1.50 trueerr("no page") err("not an int: \"two\"")

Chaining

print("next page" | url_encode)let next = "/items?page=2" | url_encodeprint(`/login?next=${next}`)
output
next%20page/login?next=%2Fitems%3Fpage%3D2
in a program
fn signed_in(r) = session().user != null ? r : reply 303 redirect(`/login?next=${url_encode(r.path)}`)

See also

escape, redirect, str

Thread
6Useful? Like it, or add to its thread below.

Thread 0 posts

On url_encode(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo