Most JavaScript developers have been bitten by URL encoding at some point. You build a query string, pass it to fetch(), and suddenly your API returns 400. The culprit? You used encodeURI() when you should have used encodeURIComponent().
The Core Difference
JavaScript gives us two encoding functions, and they serve different purposes:
encodeURI()is designed for complete URLs. It keeps URL structure characters intact:/,?,&,=,#,:,@,$,+, and,. Use it when you have a full URL string and want to make it safe for transmission.encodeURIComponent()is for individual parameter values. It encodes everything exceptA-Z a-z 0-9 - _ . ! ~ * ' ( ). This is what you want for query string values, path segments, and any data embedded in a URL.
The Classic Bug
Here's the mistake everyone makes at least once:
// WRONG — the @ and = break as literal URL characters
const email = "user@example.com";
const url = "https://api.example.com/search?email=" + encodeURI(email);
// Result: https://api.example.com/search?email=user@example.com
// The @ is interpreted as a URL authority separator!
The fix:
// RIGHT — all special chars are percent-encoded
const url = "https://api.example.com/search?email=" + encodeURIComponent(email);
// Result: https://api.example.com/search?email=user%40example.com
Double-Encoding: The Silent Killer
If you encode an already-encoded string, the % sign itself gets encoded to %25. hello%20world becomes hello%2520world. This is maddening to debug because it looks almost right. The fix: always decode first to see what you're actually working with.
The Modern Approach
In 2026, you rarely need to manually encode URLs. The URL and URLSearchParams APIs handle encoding automatically:
const params = new URLSearchParams({ email: "user@example.com", q: "hello world" });
const url = "https://api.example.com/search?" + params.toString();
// https://api.example.com/search?email=user%40example.com&q=hello+world
When You Still Need Manual Encoding
Sometimes you're debugging logs, comparing API responses, or working with encoded strings from external systems. That's when a quick encoder/decoder tool saves you from counting percent signs in your terminal.
Handy tool: I keep CodeToolbox URL Encoder bookmarked for those moments — paste any string, encode or decode instantly, all local processing so no data leaves your browser.
TL;DR: encodeURI() for full URLs. encodeURIComponent() for values. URLSearchParams for everything new. And if you see %25 in your output, you've double-encoded — decode and start over.
Top comments (0)