blog / url-encoding

URL Encoding Explained for Beginners

· 2 min read

URLs are restricted to a specific character subset defined by RFC 3986. Any character falling outside this specification (including spaces, non-ASCII diacritics, and structural delimiters like & or #) must be escaped using percent-encoding prior to transmission across HTTP networks.

Mechanism of Percent-Encoding

Percent-encoding replaces unpermitted octets with a % symbol followed by a two-digit hexadecimal representation of the character's UTF-8 byte value. For example, a space transforms to %20, an @ symbol becomes %40, and a forward slash / escapes to %2F when passed within query arguments.

RFC 3986 Character Classification

RFC 3986 divides ASCII characters into distinct functional groups:

  • Reserved Characters: Structural syntax delimiters: : / ? # [ ] @ ! $ & ' ( ) * + , ; =. When passing data containing these characters inside query parameters, they must be percent-encoded to prevent syntax parsing errors.
  • Unreserved Characters: Standard safe characters: A-Z, a-z, 0-9, -, _, ., and ~. These never require encoding.
  • Non-ASCII Octets: Unicode characters (e.g. é U+00E9) are first converted to UTF-8 multi-byte sequences, then converted into individual percent-encoded bytes (such as %C3%A9).

JavaScript Implementation: encodeURI vs encodeURIComponent

Choosing the correct native encoding API in JavaScript is critical to prevent broken links or broken API parameters:

// encodeURI preserves URL structural delimiters (: / ? # &)
const fullUrl = encodeURI("https://example.com/search?q=hello world");
// Result: "https://example.com/search?q=hello%20world"

// encodeURIComponent encodes ALL reserved characters including (& = / ?)
const queryParam = encodeURIComponent("price=10&tax=2");
// Result: "price%3D10%26tax%3D2"

Use encodeURIComponent() when formatting key-value pairs inside query strings or URL path segments. Use encodeURI() only when encoding a fully assembled web address string.

Form Submissions and application/x-www-form-urlencoded

HTML form GET/POST submissions using the application/x-www-form-urlencoded content-type apply percent-encoding with one legacy distinction: spaces are encoded as plus signs (+) instead of percent-twenties (%20).

Client-Side Encoding Tools

To safely test percent-encoding or decode URL query strings directly in your browser, use the URL Encoder and URL Decoder on TextUtils.