encodeURIComponent vs encodeURI: Which Characters Get Percent-Encoded

By · Published · Updated

A URL uses certain characters as syntax: ? starts the query string, & separates parameters, # starts a fragment, and / separates path segments. If your 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.

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 going into a URL, such as a query parameter or a path segment. It encodes those characters too, which is almost always what you want when you build 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.

Advertisement

A literal plus sign needs %2B

In a query string, + is decoded as a space (a convention from the older application/x-www-form-urlencoded spec, not part of general percent-encoding). So a value that really contains a plus sign has to be sent as %2B, or the server reads it back as a space. encodeURIComponent does this for you; hand-built strings often don't.

"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)

The reverse direction is its own surprise: URLSearchParams encodes a space as + rather than %20. That, and the other behavior of the browser's URL API, is covered in why URLSearchParams turns spaces into +.

Advertisement

Try the URL Encoder / Decoder →

Related tools & guides

Part of Encoding & Decoding Tools