JavaScript Reference Β· Global Functions and Values
The encodeURIComponent() function
Reference for encodeURIComponent(): percent-encoding query values and path segments, which characters stay unescaped, UTF-8 handling and lone surrogate errors.
encodeURIComponent() turns a string into a form that is safe to place inside one part of a URL, such as a query-string value or a path segment. Every character except a small safe set is replaced by percent-escapes of its UTF-8 bytes: a space becomes %20, & becomes %26, and Γ© becomes %C3%A9.
Use it on each value you insert into a URL. Encoding the finished URL instead would also escape the :, /, ? and = that give the URL its structure.
encodeURIComponent("a&b=c d"); // "a%26b%3Dc%20d"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
encodeURIComponent(uriComponent)
| Name | Description |
|---|---|
uriComponent |
The text to encode. Non-strings are converted to strings first, so null becomes "null". |
Return value: a new string in which all characters except letters, digits and - _ . ! ~ * ' ( ) are percent-encoded.
Exceptions: a URIError if the string contains a lone surrogate (an unpaired half of a UTF-16 pair).
Usage notes
- Encode values, not whole URLs. Apply it to each query value or path segment separately, then join them with the real
?,&and=. - Reserved characters are escaped:
; , / ? : @ & = + $ #all become percent-escapes, unlike withencodeURI(). - Spaces become
%20, not+. Form encoding (application/x-www-form-urlencoded) uses+, whichURLSearchParamsproduces. - A few characters stay literal, including
',(,),*and!. If you embed the result in HTML attributes or a stricter format, escape them yourself. - Output is always UTF-8. Servers expecting another charset need different handling.
- Never double-encode. Encoding an already-encoded string turns
%20into%2520. - Prefer
URLandURLSearchParamsfor new code; they encode for you and parse safely. See URL. - Lone surrogates throw.
String.prototype.toWellFormed()can repair such text first in newer engines.
Browser support
encodeURIComponent() is available in every browser and runtime.
Related
decodeURIComponent(),encodeURI(),URL,URLSearchParams- Lessons: Strings, Fetch