URL Encoding and Decoding Guide: Fix Query Parameters, Spaces, and Reserved Characters
URLsweb APIsJavaScriptquery parametersdebugging

URL Encoding and Decoding Guide: Fix Query Parameters, Spaces, and Reserved Characters

WWebDecodes Editorial Team
2026-12-04
7 min read

Learn when to use encodeURI, encodeURIComponent, and URLSearchParams to fix spaces, reserved characters, nested URLs, and query bugs.

Use this practical URL encoding and decoding checklist to build reliable links, handle query parameters and path segments correctly, preserve spaces and Unicode text, and diagnose URLs that behave differently across browsers, frameworks, and APIs.

Overview

URL encoding, also called percent encoding, represents characters that have a special meaning in a URL or cannot be safely transmitted as written. A space may become %20, for example, while a character such as & may become %26. The encoded form allows a browser, server, or API client to distinguish data from URL structure.

The most important decision is identifying what you are encoding. A complete URL, a path segment, a query parameter value, and form data do not follow exactly the same workflow. Encoding the wrong level can produce broken links, double-encoded values, or parameters that are interpreted as multiple fields.

For quick checks, a browser-based URL encoder or URL decoder can help you inspect a value without writing a script. Treat online developer tools as debugging aids: do not paste passwords, private access tokens, session identifiers, or other confidential data into a tool unless you have verified how it handles input.

In JavaScript, the most common building blocks are the URL, URLSearchParams, encodeURI(), and encodeURIComponent() APIs. Prefer structured APIs when constructing URLs, because they make the boundary between the URL and its individual values explicit.

Checklist by scenario

Encoding a query parameter

Query parameters carry key-value data after the ?, with pairs separated by &. Encode each value rather than manually replacing a few characters.

const url = new URL('https://example.com/search');
url.searchParams.set('q', 'red & blue');
url.searchParams.set('redirect', 'https://example.com/account?tab=billing');

console.log(url.toString());

Using URLSearchParams prevents the ampersand in red & blue from being mistaken for a separator. It also handles a nested URL as a single parameter value. If you use a lower-level function, encodeURIComponent(value) is generally the appropriate choice for an individual query value.

Encoding a path segment

A path uses slashes to separate segments. If a user-provided value belongs inside one segment, encode that value separately so characters such as /, ?, and # cannot change the path structure.

const username = 'team/blue';
const url = '/users/' + encodeURIComponent(username);
// /users/team%2Fblue

This is different from encoding an entire path. Encoding the whole path can turn meaningful separators into data, while leaving a segment unencoded can allow reserved characters to alter routing.

Preserving spaces, plus signs, and form data

There are two conventions to keep separate. General URL percent encoding represents a space as %20. The application/x-www-form-urlencoded convention commonly represents a space as +, while a literal plus sign is represented as %2B. This distinction matters when working with HTML forms, query-string parsers, and APIs that expect form-style input.

For example, the value C++ guide should not be casually converted to C+guide unless the receiving parser explicitly applies form decoding. Otherwise, the plus sign may be treated as a space. Use the serialization method expected by the endpoint and test both spaces and literal plus signs.

Encoding a complete URL

encodeURI() is intended for a complete URI and leaves structural characters such as :, /, ?, and & available as URL syntax. It is useful when a complete URL needs limited escaping, but it should not be used to encode a single query value.

encodeURIComponent() is intended for one component, such as a query value or path segment. It escapes characters that would otherwise be interpreted as separators. A useful rule is: use encodeURI() for a URL-shaped string, and encodeURIComponent() for a value placed inside a URL.

MethodBest useWatch for
encodeURI()A complete URL or URIIt preserves URL separators, so it is unsuitable for isolated parameter values
encodeURIComponent()One query value or path segmentIt can encode characters you intended to keep as URL structure
URLSearchParamsBuilding and reading query stringsIts serialization follows form-style query conventions, including treatment of spaces
Browser URL toolsInspecting a value, comparing encoded and decoded forms, and reproducing bugsNever assume sensitive input is appropriate for a third-party service

Handling Unicode text

Unicode characters such as accented letters, non-Latin scripts, and emoji are represented through UTF-8 percent-encoded bytes when placed in a URL. Do not assume that visual characters and transmitted bytes are interchangeable. Test the exact string, including normalization-sensitive text, at the same boundary where your application constructs or parses the URL.

Decoding a URL or value

Decode only the layer you know was encoded. Use decodeURIComponent() for an individual component and decodeURI() for a complete URI. A malformed percent sequence can throw an error in JavaScript, so production code should handle invalid input instead of assuming every external URL is well formed.

try {
  const value = decodeURIComponent(input);
  console.log(value);
} catch {
  console.error('The value is not valid percent-encoded text.');
}

When parsing query data, prefer new URL(requestUrl).searchParams or the equivalent framework parser. These tools preserve the difference between parameter names, values, repeated parameters, and the absence of a parameter.

What to double-check

  • Encoding boundary: Confirm whether the input is a complete URL, a path segment, a parameter name, or a parameter value.
  • Reserved characters: Check &, =, ?, #, /, and +. Each can be syntax or data depending on its position.
  • Fragments: A # fragment is handled by the browser and is not normally sent to the server in an HTTP request. Encode a literal hash inside a value as %23.
  • Repeated parameters: Decide whether ?tag=a&tag=b means a list. Do not assume every framework returns only the first value.
  • Nested URLs: Encode the inner URL as a value once. Inspect the final request to confirm its own ? and & did not become outer query syntax.
  • Existing encoding: Determine whether an input is already encoded before encoding it again. A literal percent sign may become %25, producing values such as %2520 after double encoding.
  • Server and client agreement: Compare what the browser sends with what the server, router, proxy, or API library parses. The Browser DevTools Network tab is useful for checking the actual request URL, headers, redirects, and response.

For broader request investigations, see the Browser DevTools Network Tab Guide and API Request Debugging with cURL. If a malformed URL appears during deployment, review the Website Deployment Checklist as well.

Common mistakes

  1. Replacing spaces by hand: Simple string replacement does not handle ampersands, Unicode, plus signs, or other reserved characters consistently.
  2. Using encodeURI() for a parameter: An ampersand in the value can become a new parameter, and an equals sign can change how the value is parsed.
  3. Decoding too early: Decode at the boundary where data becomes application data. Decoding a complete URL before routing or parsing can reintroduce structural characters.
  4. Decoding twice: Repeated decoding can change legitimate data and may create unexpected delimiters.
  5. Confusing display and transport: A browser may display a readable character while the request uses its encoded representation. Inspect the request and the parsed value rather than relying only on the address bar.
  6. Logging sensitive query strings: Query parameters can appear in browser history, server logs, analytics systems, and referrer-related data. Avoid putting secrets in URLs and redact sensitive values from debugging output.

If your workflow also generates links inside documentation, preview the final rendered URL and test it from a clean browser session. The Markdown Documentation Workflow provides a useful companion process for reviewing links before publication.

When to revisit

Revisit this checklist whenever you change a router, API client, framework, form submission method, proxy, redirect rule, or URL-generation utility. It is also worth checking before launching a feature that accepts search terms, filters, referral parameters, redirect destinations, or user-generated path values.

For a focused debugging pass, run this sequence:

  1. Start with one failing input, including spaces, an ampersand, a plus sign, a Unicode character, or a nested URL.
  2. Record the intended logical value before encoding.
  3. Construct the URL with URL, URLSearchParams, or the appropriate component encoder.
  4. Inspect the exact request in browser developer tools or with a command-line client.
  5. Compare the server's parsed value with the original logical value.
  6. Test empty values, repeated parameters, malformed percent sequences, and already encoded input.
  7. Document the endpoint's expected encoding convention so the next implementation does not have to infer it.

Keep this process alongside other developer workflow tools, especially when URLs are produced by multiple services. A small difference between form encoding, component encoding, and framework parsing can be enough to make a link work in one environment and fail in another.

Related Topics

#URLs#web APIs#JavaScript#query parameters#debugging
W

WebDecodes Editorial Team

Developer Tools Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.