nTropi
Article·

URL Encoding Explained

Why URLs need encoding, what percent-encoding is, and the difference between encodeURI and encodeURIComponent.

Why URLs Need Encoding

URLs can only contain a limited set of ASCII characters. Spaces, non-ASCII characters, and reserved characters (&, =, ?, #) must be encoded.

Percent-Encoding

Reserved and unsafe characters are replaced with %XX where XX is the hex byte value.

Examples:

  • Space → %20 (or + in query strings)
  • &%26
  • =%3D
  • /%2F

encodeURI vs encodeURIComponent

encodeURI("https://example.com/path?q=hello world")
// → "https://example.com/path?q=hello%20world"
// Does NOT encode: : / ? # [ ] @ ! $ & ' ( ) * + , ; =

encodeURIComponent("hello & world")
// → "hello%20%26%20world"
// Encodes everything except: A-Z a-z 0-9 - _ . ! ~ * ' ( )

Rule: use encodeURIComponent for query parameter values. Use encodeURI for full URLs.

Encode and decode URLs instantly with the URL Encoder/Decoder.