The short answer
- Use
encodeURIComponent()for a piece of a URL: a query value, a path segment, a fragment. - Use
encodeURI()for a complete URL that is mostly fine but may contain spaces or non-ASCII characters. - Never use
escape(). It is deprecated and does not produce UTF-8 for characters above U+00FF.
Same input, different results
For the text a b/c?d=e&f+g~(h)*!':
| Function | Result |
|---|---|
encodeURIComponent | a%20b%2Fc%3Fd%3De%26f%2Bg~(h)*!' |
encodeURI | a%20b/c?d=e&f+g~(h)*!' |
Form style (+) | a+b%2Fc%3Fd%3De%26f%2Bg%7E%28h%29*%21%27 |
| RFC 3986 strict | a%20b%2Fc%3Fd%3De%26f%2Bg~%28h%29%2A%21%27 |
escape (deprecated) | a%20b/c%3Fd%3De%26f+g%7E%28h%29*%21%27 |
The table above is for one fixed string. The tool at the top of the page fills in the same table for your own text, with a Copy button for each row.
What each one leaves alone
| Function | Characters not encoded |
|---|---|
encodeURIComponent | A-Z a-z 0-9 - _ . ! ~ * ' ( ) |
encodeURI | The same, plus ; , / ? : @ & = + $ # |
| RFC 3986 strict | A-Z a-z 0-9 - . _ ~ |
The characters that encodeURI keeps are exactly the ones that give a URL its structure. That is why it is right for a whole link and wrong for a value: a value that contains & or # would break the URL.
A typical bug
// Wrong: the & in the name ends the parameter early
const url = 'https://example.com/?name=' + encodeURI('Tom & Jerry');
// ...?name=Tom%20&%20Jerry -> name is "Tom ", plus a new parameter
// Right
const url = 'https://example.com/?name=' + encodeURIComponent('Tom & Jerry');
// ...?name=Tom%20%26%20Jerry
Other languages
| Language | Value (component) | Form style (+) |
|---|---|---|
| JavaScript | encodeURIComponent() | URLSearchParams |
| PHP | rawurlencode() | urlencode() |
| Python | urllib.parse.quote(s, safe='') | quote_plus() |
| Java | URLEncoder.encode(...) then replace + with %20 | URLEncoder.encode(s, UTF_8) |
| C# | Uri.EscapeDataString() | WebUtility.UrlEncode() |
Careful with Python: quote() leaves / unencoded unless you pass safe=''.
More: URL encoder, percent-encoding tool and the URL encoding guide.