Quick answer: URL encoding, also called percent-encoding, replaces characters that are not allowed or have a special meaning in a URL with a percent sign followed by two hexadecimal digits. A space becomes %20 and an ampersand becomes %26. You can convert text either way with the URL encoder and decoder.

Why URLs Need Encoding

A URL may only contain a limited set of characters. Some characters carry meaning: ? starts the query string, & separates parameters, # starts the fragment. If your data contains those characters, it must be encoded or it will be misread as part of the URL's structure.

For example, searching for fish & chips must be sent as fish%20%26%20chips. Without encoding, the & would be read as the start of a new parameter.

Which Characters Are Safe?

The unreserved characters never need encoding: letters A to Z and a to z, digits 0 to 9, and - . _ ~. Everything else is either reserved for URL syntax or must be encoded.

How Non-English Characters Are Encoded

Characters outside basic ASCII are first converted to UTF-8 bytes, and each byte is percent-encoded. The letter é becomes %C3%A9, and the euro sign € becomes %E2%82%AC.

Spaces: %20 or +?

In a URL path, a space is always %20. In HTML form data and many query strings, a space may also appear as +. When decoding query strings, treat + as a space; when decoding paths, do not.

encodeURI vs encodeURIComponent

  • encodeURIComponent encodes almost everything, including / ? & = #. Use it for a single value, such as one query parameter.
  • encodeURI leaves those structural characters alone. Use it on a whole URL you want to keep working.

Encoding a full URL with the component method breaks it, because the slashes and colons are encoded too. Encode the parts, not the whole address.

Common Problems

  • Double encoding: encoding text that is already encoded turns %20 into %2520. If you see %25 in a URL, decode it once more.
  • Malformed sequences: a literal % that is not followed by two hex digits cannot be decoded. Encode it as %25.

Building a link for print? Encode it first, then turn it into a QR code.