Nyx by Example

URL Encode

std/url provides percent-encoding for URLs (RFC 3986), query string building, and HTML entity escaping. These are fundamental for building web clients and servers that handle user input safely.

Code

// URL encoding, decoding, and query string building

import "std/url"

fn main() -> int {
    let raw: String = "hello world & foo=bar"
    let encoded: String = url_encode(raw)
    print("encoded: " + encoded)

    let decoded: String = url_decode(encoded)
    print("decoded: " + decoded)

    let keys: Array = ["name", "lang", "version"]
    let vals: Array = ["Nyx Lang", "es", "0.12"]
    let qs: String = build_query_string(keys, vals)
    print("query:   " + qs)

    let html: String = html_escape("<script>alert('xss')</script>")
    print("escaped: " + html)

    return 0
}

Output

encoded: hello%20world%20%26%20foo%3Dbar
decoded: hello world & foo=bar
query:   name=Nyx%20Lang&lang=es&version=0.12
escaped: &lt;script&gt;alert('xss')&lt;/script&gt;

Explanation

url_encode percent-encodes all characters except RFC 3986 unreserved characters (A-Z, a-z, 0-9, -._~). Spaces become %20, ampersands become %26, etc. url_decode reverses the process and also decodes + as space.

build_query_string takes parallel arrays of keys and values, encodes each pair, and joins them with &. This is the standard format for URL query parameters and HTML form submissions.

html_escape converts the five HTML-sensitive characters (& < > " ') to their entity equivalents. Always escape user input before inserting it into HTML to prevent XSS attacks.

← Previous Next →

Source: examples/by-example/42-url-encode.nx