asUrlEncoded
Module Export
text |> textPercent-encodes a text value so it can safely be used as a URL query parameter value (RFC 3986).
asUrlEncoded percent-encodes a text value so it is safe to place in a URL — typically as a query parameter value, but it works equally well for a path segment.
Encoding follows RFC 3986: every character outside the unreserved set is replaced by one or more %XX escapes of its UTF-8 bytes. The unreserved set is:
A-Z a-z 0-9 - _ . ~Everything else — including &, =, ?, /, #, +, % and spaces — is escaped. A space becomes %20, not +.
Examples
Encode a query parameter value
import { asUrlEncoded } from 'text'
from 'blue & green shoes' asUrlEncoded
// Returns: 'blue%20%26%20green%20shoes'Build a URL from a parameter
import { asUrlEncoded } from 'text'
param search: text = 'blue & green shoes'
let encoded = search asUrlEncodedfrom 'https://example.com/find?q=' + encoded
// Returns: 'https://example.com/find?q=blue%20%26%20green%20shoes'Encoding each value separately is what keeps the URL unambiguous. Without it, a value containing & or = would be read by the receiver as the start of another parameter.
Reserved characters are escaped
import { asUrlEncoded } from 'text'
from 'a b&c=d?e/f#g' asUrlEncoded
// Returns: 'a%20b%26c%3Dd%3Fe%2Ff%23g'Unreserved characters pass through
import { asUrlEncoded } from 'text'
from 'AZaz09-_.~' asUrlEncoded
// Returns: 'AZaz09-_.~'Non-ASCII characters become UTF-8 escapes
import { asUrlEncoded } from 'text'
from 'Åke på café' asUrlEncoded
// Returns: '%C3%85ke%20p%C3%A5%20caf%C3%A9'Notes
- A space is encoded as
%20. The+convention for spaces only applies toapplication/x-www-form-urlencodedcontent (HTML form bodies), not to URLs in general, so a literal+in the input is escaped to%2B !,',(,)and*are sub-delimiters rather than unreserved characters, so they are escaped (%21,%27,%28,%29,%2A)%is escaped to%25. ApplyingasUrlEncodedto text that is already encoded will therefore double-encode it — encode raw values only, once- Encode individual values, not a whole URL or query string. Encoding
a=1&b=2as one text escapes the=and&that give it structure
See Also
- asUrlDecoded to reverse the encoding
- encode and decode for converting between text and bytes (Base64, hex, UTF-8). Those work on
[byte], whereasasUrlEncodedistext |> text