URL Encoding: Percent-Encode Query Parameters and Paths

Percent-encoding replaces unsafe characters with %XX so arbitrary text is safe in a URL. Know which characters to escape and how to decode them back.

What percent-encoding is

Characters that are not allowed in a URL are replaced with a percent sign and two hex digits. A space becomes %20 and an ampersand becomes %26.

encodeURIComponent vs encodeURI

Use encodeURIComponent for a single query value or path segment — it escapes /, ?, &, and =. Use encodeURI only on a whole URL, where those characters are structural and must survive.

The plus vs %20 trap

In query strings a space can appear as a plus sign (form encoding) or as %20. decodeURIComponent does not turn a plus into a space, so replace plus signs before decoding form-encoded data.

Double-encoding

Encoding an already-encoded string turns %20 into %2520. If you see %25 sequences in the output, the value was encoded twice — decode it repeatedly until it stops changing.

Reserved versus unreserved characters

RFC 3986 splits URL characters into reserved (gen-delims like : / ? # and sub-delims like & =) and unreserved (letters, digits, - . _ ~). Unreserved characters never need encoding. Reserved characters only need encoding when they appear inside a value rather than as URL structure.

Encoding a full URL versus a single value

encodeURI is for whole URLs: it leaves : / ? # & = alone so the URL keeps its shape. encodeURIComponent is for one value going into a path segment or query parameter — it escapes those structural characters so the value cannot break out of its slot.

Building safe query strings programmatically

Prefer URLSearchParams (browser) or url.URLSearchParams (Node) over string concatenation. Both APIs encode keys and values correctly, handle multi-value parameters, and avoid the most common mistake — forgetting to encode a parameter that happens to contain & or =.