FAQ
Q: What's the difference between encodeURI and encodeURIComponent?
encodeURI is meant for encoding a complete URI—it leaves structurally significant characters like :, /, ?, #, &, and = untouched. encodeURIComponent is meant for encoding a single URI component (such as a query parameter value) and encodes nearly every special character. For example, applying encodeURI to https://example.com/search?q=hello world only encodes the space, while encodeURIComponent also encodes ://, /, ?, and =. Use encodeURIComponent when building query strings to avoid breaking the URL structure.
Q: Why do non-ASCII characters become %XX sequences in URLs?
The URL specification (RFC 3986) restricts URIs to a subset of ASCII characters. Characters outside that set—such as Chinese, accented letters, or emoji—must be percent-encoded before they can appear in a URL. The process converts each character to its UTF-8 byte representation and then writes each byte as % followed by two hexadecimal digits. For instance, the character "ñ" is C3 B1 in UTF-8, so it appears as %C3%B1 in a URL.
Q: What's the difference between URL encoding and Base64 encoding?
They serve different purposes. URL encoding (percent-encoding) makes special and non-ASCII characters safe for use within URLs—unaffected characters remain readable. Base64 encoding converts arbitrary binary data into a pure ASCII string and is commonly used to embed binary content in text-based formats like JSON, XML, or email. Base64 transforms all input, so the output is not human-readable. The two can be combined: for example, you might need to URL-encode a Base64 string when placing it in a query parameter.
Q: What is double encoding, and how do I avoid it?
Double encoding occurs when an already-encoded string is encoded again, turning each % into %25. For example, hello world encodes to hello%20world; encoding that a second time produces hello%2520world, which the server would decode back to the encoded form rather than the original text. This typically happens when multiple layers of a framework each apply encoding independently. To avoid it, designate a single point in your code that's responsible for encoding—usually right before the final URL is assembled—and don't encode at intermediate steps.
Q: Should spaces be encoded as %20 or +?
Both are used, but in different contexts. In URL paths and general URI components, spaces should be %20 per RFC 3986. In application/x-www-form-urlencoded data (the default format for HTML form submissions), spaces are represented as +—a historical convention. In JavaScript, encodeURIComponent produces %20, while URLSearchParams produces +. Most servers handle both correctly, but for consistency outside of form data, prefer %20.