Developer Documentation
JavaScript
Updated September 19, 2026

URL Encoding and Decoding in JavaScript

Percent-encode URL components correctly and distinguish path, query, and form encoding in JavaScript.

URL encoding is context-sensitive. A path segment, a query value, and application/x-www-form-urlencoded data do not use exactly the same escaping rules, so prefer APIs designed for the specific component you are building.

Quick Start#

The following example uses the standard JavaScript API or a widely used package for this task.

Encode a component#

JavaScript
1const value = "café & tea + cake";2const encoded = encodeURIComponent(value);3const decoded = decodeURIComponent(encoded);45console.log(encoded);6console.log(decoded);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Build query strings with URLSearchParams#

JavaScript
1const params = new URLSearchParams({2  q: "café & tea",3  page: "1",4});5const url = `https://example.com/search?${params.toString()}`;6console.log(url);

Important Notes#

URLSearchParams uses form-style query encoding where spaces can appear as +; encodeURIComponent uses percent-encoding such as %20.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement URL Encoding in other languages: