Back to Blog
Developer Tools

URL Encode Query Parameters โ€” Handle Special Characters in API Requests

2026-06-03 4 min read

Spaces, ampersands, and equal signs break URLs when unencoded. Here is when to encode query parameters and what characters require encoding.

Building URLs dynamically is something every web developer does. And it's something a lot of developers get wrong, especially when the values contain spaces, ampersands, or special characters. Improper URL encoding causes subtle bugs that are hard to track down.

Why query parameters need encoding

A URL query string uses specific characters for structure: ? starts it, & separates parameters, and = connects keys to values. If any of those characters appear inside a value, the parser gets confused.

Say you want to build this search URL: https://example.com/search?q=C++ programming&lang=en

The + characters in the query will be interpreted as spaces by most servers (legacy form encoding). The actual intent is broken. The correct URL is: https://example.com/search?q=C%2B%2B%20programming&lang=en

The right functions to use

JavaScript has two encoding functions that get confused often:

// encodeURIComponent โ€” encodes EVERYTHING except A-Z a-z 0-9 - _ . ! ~ * ' ( )
// Use this for query parameter VALUES
encodeURIComponent("hello world & more") // "hello%20world%20%26%20more"
encodeURIComponent("C++ programming")    // "C%2B%2B%20programming"

// encodeURI โ€” leaves URL structure characters alone (: / ? & = #)
// Use this for complete URLs you don't want to break
encodeURI("https://example.com/search?q=hello world")
// "https://example.com/search?q=hello%20world"

Building URLs safely

The best approach for building URLs with dynamic parameters is the URL and URLSearchParams browser APIs. They handle encoding automatically:

const url = new URL("https://example.com/search");
url.searchParams.set("q", "C++ programming");
url.searchParams.set("lang", "en");
url.searchParams.set("page", "1");

console.log(url.toString());
// https://example.com/search?q=C%2B%2B+programming&lang=en&page=1

Note that URLSearchParams uses + for spaces (form encoding). Both + and %20 decode to a space, so both are valid in query strings.

Common mistake: double encoding

If you encode a value, then pass it to something that encodes it again, you end up with %2520 instead of %20(the % itself gets encoded as %25). This breaks the URL. Pick one encoding layer and stick to it.

Encode and decode URL parameters with our URL Encoder tool.

url encode query parameters api http

More Articles