URL Encoding Explained
URL encoding (percent-encoding) replaces characters that aren't allowed in URLs with a % followed by their hexadecimal ASCII code. For example, a space becomes %20, "/" becomes %2F. This ensures URLs are transmitted correctly through all systems.
Characters That Must Be Encoded
- Space → %20 (or + in query strings)
- & → %26 (separates query params, must be encoded in values)
- = → %3D (separates key from value)
- ? → %3F (starts query string)
- # → %23 (starts fragment)
encodeURI vs encodeURIComponent
- encodeURI(): encodes a full URL, preserving :, /, ?, #, & — use for complete URLs
- encodeURIComponent(): encodes everything including :, /, ?, & — use for individual parameter values
- Example: for a query param value "hello world & more", use encodeURIComponent → "hello%20world%20%26%20more"
Why do URLs sometimes use + instead of %20 for spaces?
The + sign as space replacement comes from HTML form encoding (application/x-www-form-urlencoded). When a browser submits a form via GET, spaces are encoded as + rather than %20. Most servers understand both, but %20 is the more universal standard (RFC 3986). In query strings + and %20 are usually interchangeable; in path segments, use %20 — a + in the path is treated as a literal plus sign.
How do I encode a full URL that already has query parameters?
Use encodeURIComponent() only on parameter values, not the entire URL. Encoding the whole URL breaks the URL structure by encoding ?, &, and =. The correct approach: build the URL structure normally, then encode each parameter value: `https://example.com/search?q=${encodeURIComponent(userInput)}`.