Skip to content
ToolzKit

Guide · 5 min read

URL encoding explained

A URL has a grammar. Slashes separate path segments, question marks start a query, ampersands separate parameters and hashes begin a fragment. Percent-encoding is how you include one of those characters as data rather than as punctuation, and getting it wrong is one of the most common causes of broken links and lost query parameters.

What percent-encoding does

Each byte that needs escaping is written as a percent sign followed by two hexadecimal digits. A space becomes %20, an ampersand becomes %26. Non-ASCII characters are first converted to UTF-8, then each byte is escaped, so an accented character usually becomes two percent groups.

encodeURI versus encodeURIComponent

encodeURI is for a whole URL: it deliberately leaves the structural characters alone so the address still works. encodeURIComponent is for a single value going into a path segment or a query parameter: it escapes slashes, ampersands and question marks too.

The rule of thumb is simple. If you are escaping a piece of data, use encodeURIComponent. If you are cleaning up a complete address someone typed, use encodeURI.

  • encodeURIComponent('a&b') → a%26b — safe as a parameter value.
  • encodeURI('https://x.test/a b') → https://x.test/a%20b — the structure survives.

The plus-sign confusion

In the application/x-www-form-urlencoded format used by HTML form submissions, a space is encoded as a plus sign rather than %20. Outside that context a plus sign means a literal plus. That is why our decoder offers a toggle: decoding form data and decoding a path segment are genuinely different operations.

Double encoding

Encoding an already-encoded string turns %20 into %2520, because the percent sign itself gets escaped. If you see %25 appearing in your links, something in the chain is encoding twice — usually a template that escapes a value that a framework already escaped.