encodeURIComponent()
For one VALUE inside a URL — a query parameter, a path segment. encodeURI is for a whole URL and deliberately leaves the structural characters intact, which makes it the wrong choice for values.
Demo
The pair is [encodeURIComponent, encodeURI]. The first case is the decision in one line: for the text 'a b&c=d', encodeURIComponent escapes the & and = because inside a single value they would be mistaken for structure, while encodeURI leaves them because in a whole URL that is exactly what they are. The second case shows the mirror image — encodeURI keeps a URL usable, encodeURIComponent destroys it by escaping the slashes and colon. Accented characters become UTF-8 byte sequences in both. Note the fourth case: several punctuation characters are NOT escaped by either.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| string | string | yes | The text to escape. Non-strings are converted first. A lone surrogate — from slicing an emoji in half — throws URIError. |
Return value
string — The string with every character escaped except A–Z a–z 0–9 and - _ . ! ~ * ' ( ). Non-ASCII characters become UTF-8 percent sequences.
Common patterns
const q = new URLSearchParams({name: value}).toString();
const url = `/users/${encodeURIComponent(id)}`;
const safe = encodeURI(urlWithSpaces);
Examples
Pitfalls
'?q=' + encodeURI('a&admin=1')
'?q=' + encodeURIComponent('a&admin=1')
encodeURIComponent("it's")
encodeURIComponent("it's").replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
encodeURIComponent('\u{1F600}abc'.slice(0, 1))
encodeURIComponent('\u{1F600}abc'.slice(0, 1).toWellFormed())
encodeURIComponent('a b')
new URLSearchParams({q: 'a b'}).toString()
When to use
- Escaping one query-parameter value
- Escaping a path segment that may contain reserved characters
- Anywhere a value is concatenated into a URL by hand
- Building a whole query string → URLSearchParams
- Fixing an existing URL with spaces → encodeURI
- HTML escaping → this is not an HTML escaper
- escape() → deprecated and wrong for non-Latin-1
Notes
FAQ
Component for a VALUE going into a URL; encodeURI for a whole URL that needs tidying. The test: if the text could legitimately contain a & or / that is data rather than structure, you need encodeURIComponent.
encodeURIComponent(value); // one piece encodeURI(wholeUrl); // an entire URL