
URL Encoding Explained: %20, +, Query Strings, and Common API Bugs
A URL is not one string with one encoding rule.
Spots 

A URL is not one string with one encoding rule.

It has a scheme, host, path, query string, fragment, and sometimes user-controlled values inside those parts. Bugs appear when code treats all of them as interchangeable text.
The familiar examples are spaces encoded as %20 or +, a literal plus sign that turns into a space, and an API request whose query parameters break when a user enters & or #. The fix starts with a simple question: what exactly are you encoding? Percent-encoding protects structure Some characters have structural meaning in a URL:
If one of those characters belongs to user-provided data, it must be encoded before it is placed into the relevant URL component. For example, this search term is data: If it is inserted directly into a query string, the & can be read as the start of another parameter: The intended value should instead be encoded:
Percent-encoding represents bytes with % followed by hexadecimal digits. A space can become %20, & becomes %26, and a literal plus sign becomes %2B.
MDN has a useful overview of percent-encoding in URLs, including why the same character may be encoded differently in different contexts. Why %20 and + both mean space sometimes This is where many API bugs begin. For an ordinary URL component, a space is commonly represented as %20:
HTML form encoding uses a related but different convention. In application/x-www-form-urlencoded data, a space is serialized as +: Both strings can represent the same value in the right context.
The important distinction is that a literal plus sign is not a space. If the original value is C++ guide, a form-style query must encode the plus signs as %2B: When that query string is parsed, + becomes a space and %2B becomes a literal plus sign.
URLSearchParams follows the application/x-www-form-urlencoded rules. MDN documents that its string parser decodes + as a space, and its serializer writes spaces as +. Read the URLSearchParams reference. encodeURI and encodeURIComponent solve different problems JavaScript provides two similarly named functions. They should not be swapped casually.
encodeURI() assumes that the input is already a complete URI. It preserves URL punctuation such as :, /, ?, &, =, and #. encodeURIComponent() is for one component or value. It encodes a wider set of characters, including &, =, and #. This is unsafe when value comes from a user: The & remains structural. The server may interpret part of the value as another query parameter. For an individual value, use encodeURIComponent(): For a full URL with query parameters, the URL and URLSearchParams APIs are usually clearer: The serialized space appears as + because searchParams uses form-style query encoding. The value remains correct.
A URL is not one string with one encoding rule.
