URL Encoding (Percent-Encoding) Explained

Published

URLs can only contain a limited set of characters, and some of those, such as ? & = and #, have special meanings. Percent-encoding replaces other characters with % and a hexadecimal byte value so any text can be placed safely in a URL.

How percent-encoding works

Each byte that needs encoding is written as % followed by two hexadecimal digits. Text is first converted to UTF-8, so a character can become several encoded bytes:

CharacterEncoded
space%20
&%26
=%3D
?%3F
/%2F
#%23
é%C3%A9
€%E2%82%AC

Characters that never need encoding

RFC 3986 defines unreserved characters that are always safe: letters A–Z a–z, digits 0–9, and - . _ ~. Reserved characters such as : / ? # [ ] @ ! $ & ' ( ) * + , ; = have special meaning in some parts of a URL and must be encoded when they are data.

encodeURIComponent versus encodeURI

JavaScript offers two functions with different purposes:

  • encodeURIComponent encodes everything except letters, digits and - _ . ! ~ * ' ( ). Use it for one value, such as a query parameter.
  • encodeURI leaves URL structure characters such as / ? & = alone. Use it only for a complete URL that is already structured correctly.
const q = "shoes & socks";
"https://shop.test/search?q=" + encodeURIComponent(q)
// https://shop.test/search?q=shoes%20%26%20socks

Convert Ferry's URL Encode uses the encodeURIComponent rules, so its output is safe as a parameter value.

Spaces: %20 or +?

In the application/x-www-form-urlencoded format used by HTML forms, a space in the query string is written as +. In other parts of a URL, + is a literal plus sign. URL Decode treats + as a plus sign; if your value came from a form submission, replace + with a space first.

Putting JSON in a query string

Sometimes a filter or state object has to travel in a URL. Minify it first to keep it short, then encode it:

{"status":"open","tags":["a","b"]}
%7B%22status%22%3A%22open%22%2C%22tags%22%3A%5B%22a%22%2C%22b%22%5D%7D

JSON URL Encode validates and minifies in one step, and JSON URL Decode turns such a value back into readable JSON. For large or sensitive data, prefer a request body: URLs are logged by servers and proxies and have practical length limits.

Common mistakes

  • Double encoding: encoding an already encoded value turns %20 into %2520.
  • Encoding the whole URL with encodeURIComponent: this encodes the :// and slashes and breaks the URL.
  • Not encoding at all: an & in a value silently splits it into two parameters.

Frequently asked questions

Is URL encoding a security measure?

No. It keeps URLs well-formed. It does not hide data, and URLs often end up in logs.

Why does %E2%82%AC decode to one character?

It is the three-byte UTF-8 sequence for the euro sign.

What is the maximum length of a URL?

There is no single limit in the standard, but browsers, servers and proxies impose their own, so keep URLs reasonably short.

Related guides