JavaScript Reference ยท Global Functions and Values
The decodeURIComponent() function
Reference for decodeURIComponent(): reversing percent-encoding, handling plus signs, malformed sequences that throw URIError, and safe decoding patterns.
decodeURIComponent() reverses encodeURIComponent(). It finds every %XX escape in a string, treats the bytes as UTF-8 and replaces them with the characters they represent. Unlike decodeURI(), it decodes reserved characters too, so %26 becomes & and %2F becomes /.
Decode a value after you have split the URL into parts, not before. Decoding first can turn an escaped & into a real separator and change the meaning.
decodeURIComponent("caf%C3%A9%20au%20lait"); // "cafรฉ au lait"
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
decodeURIComponent(encodedURIComponent)
| Name | Description |
|---|---|
encodedURIComponent |
The text to decode. Non-strings are converted to strings first. |
Return value: a new string with all percent-escapes replaced by the characters they encode.
Exceptions: a URIError if a % is not followed by two hexadecimal digits, or if the escaped bytes are not valid UTF-8.
Usage notes
- Malformed input throws. Text from users or the address bar can contain a stray
%. Wrap calls intry...catchwhen the source is not under your control. +is left alone. HTML form data uses+for a space; replace it yourself before decoding, or useURLSearchParams, which handles it.- Decode once. Decoding twice can change data that legitimately contained
%25, and double decoding is a known source of security bugs. - Escapes must form valid UTF-8.
%C3alone is an incomplete sequence and throws, while%C3%A9isรฉ. - Not a sanitizer. Decoded text can contain
<, quotes and slashes. Treat it as untrusted before putting it into HTML or file paths. - Prefer
URLobjects:new URL(text).searchParams.get("q")returns the decoded value directly.
Browser support
decodeURIComponent() is available in every browser and runtime.
Related
encodeURIComponent(),decodeURI(),URLSearchParams- Lessons: Strings, Errors