encodeURI vs encodeURIComponent
JavaScript ships two URL-encoding functions, and picking the wrong one is one of the most common — and quietest — bugs in web development. Here is the difference in one table and one rule.
What each one escapes
| Input | encodeURI | encodeURIComponent |
|---|---|---|
| hello world | hello%20world | hello%20world |
| a&b=c | a&b=c (unchanged!) | a%26b%3Dc |
| https://x.com/p?q=1 | https://x.com/p?q=1 | https%3A%2F%2Fx.com%2Fp%3Fq%3D1 |
| 50% | 50%25 | 50%25 |
encodeURI treats its input as a complete URL, so it leaves structural
characters alone: : / ? # & = + @. encodeURIComponent treats its input
as a single value and escapes all of those.
The bug that slips through
Say a user searches for fish & chips and you build the URL with encodeURI:
/search?q=fish & chips → /search?q=fish%20&%20chips
The & survived — so the server sees a parameter q=fish%20 and a second
garbage parameter %20chips. The search silently returns wrong results. With
encodeURIComponent the value arrives intact as fish%20%26%20chips.
The rule
- Building a query parameter, path segment, or form value → encodeURIComponent. This is 95% of cases.
- Cleaning up a URL you already have as a whole → encodeURI.
- Even better for query strings:
new URLSearchParams({q: value})handles encoding for you.
Try both live
The converter on the home page has a toggle for each function, so you can paste your exact string and see precisely what changes — plus a parser that decodes every parameter of any URL.