← All guides

URL Encoding: When You Need It and When You Don’t

A URL uses certain characters as syntax — ? starts the query string, & separates parameters, # starts a fragment, / separates path segments. If your actual data contains one of these characters, it has to be percent-encoded (%3F for ?, and so on) or the URL parser will misinterpret where one part ends and the next begins.

The space character, three different ways

This is the most common source of confusion. In a URL path, a space is encoded as %20. In a query string, both %20 and + are used to mean space — but + is a query-string-specific convention (from the older application/x-www-form-urlencoded spec), not part of general percent-encoding. If you encode a literal + character that's meant to be a plus sign in a query string, it needs to become %2B, or it'll be decoded back as a space.

"a+b"        as a query value → means "a b" (plus decodes to space)
"a%2Bb"      as a query value → means "a+b" (literal plus, correctly escaped)

encodeURIComponent vs encodeURI

JavaScript has two built-ins and picking the wrong one is a common bug. encodeURI is meant for encoding a full URL and deliberately leaves characters like /, ?, and & untouched, because it assumes you're passing in something that's already structured as a URL. encodeURIComponent is for encoding a single value that's going into a URL — a query parameter, a path segment — and it encodes those characters too, which is almost always what you actually want when you're building a URL piece by piece.

encodeURI("a/b?c=1")            // "a/b?c=1"        (unchanged — treated as a full URL)
encodeURIComponent("a/b?c=1")   // "a%2Fb%3Fc%3D1"  (fully escaped — treated as one value)

If you're assembling a query string parameter-by-parameter, use encodeURIComponent on each value. Using encodeURI there is the classic mistake that leaves & and = inside a value unescaped, which then gets misread as additional parameters.

Try the URL Encoder / Decoder