encodeURIComponent vs encodeURI: What's the Difference?
JavaScript has two built-in URL-encoding functions, and using the wrong one is a common bug. Here's the difference.
The short answer
encodeURIComponent— use for a single piece of data (a query parameter value, a path segment).encodeURI— use for an entire URL you don't want to break apart.
Why they differ
encodeURI assumes you're encoding a complete URL, so it leaves URL structure characters alone: : / ? # & = stay as-is. encodeURIComponent assumes you're encoding a value, so it encodes those characters too.
encodeURI('https://x.com/a b?q=1&r=2');
// "https://x.com/a%20b?q=1&r=2" — structure preserved
encodeURIComponent('a b?q=1&r=2');
// "a%20b%3Fq%3D1%26r%3D2" — everything encoded
The common bug
Building a query string with encodeURI lets & and = through, so a value containing them breaks your parameters:
// ❌ wrong — the & in the value is not encoded
'?q=' + encodeURI('tom & jerry');
// ✅ right
'?q=' + encodeURIComponent('tom & jerry');
Rule of thumb
- Encoding one value →
encodeURIComponent - Encoding a whole URL string →
encodeURI
When in doubt for query parameters, it's almost always encodeURIComponent. See when to URL-encode query parameters.
Try it
The URL encoder/decoder shows you the encoded result so you can verify which characters get escaped.
Got a config file to check?
Open the config toolkit →