Path: blob/main/files/en-us/web/javascript/reference/global_objects/encodeuricomponent/index.md
6529 views
------{{jsSidebar("Objects")}}
The encodeURIComponent() function encodes a {{glossary("URI")}} by replacing each instance of certain characters by one, two, three, or four escape sequences representing the {{glossary("UTF-8")}} encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to {{jsxref("encodeURI()")}}, this function encodes more characters, including those that are part of the URI syntax.
{{EmbedInteractiveExample("pages/js/globalprops-encodeuricomponent.html","shorter")}}
Syntax
Parameters
uriComponent: A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are converted to strings.
Return value
A new string representing the provided uriComponent encoded as a URI component.
Exceptions
{{jsxref("URIError")}}
: Thrown if
uriComponentcontains a lone surrogate.
Description
encodeURIComponent() is a function property of the global object.
encodeURIComponent() uses the same encoding algorithm as described in {{jsxref("encodeURI()")}}. It escapes all characters except:
Compared to {{jsxref("encodeURI()")}}, encodeURIComponent() escapes a larger set of characters. Use encodeURIComponent() on user-entered fields from forms {{HTTPMethod("POST")}}'d to the server — this will encode & symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes Jack & Jill, without encodeURIComponent(), the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.
For application/x-www-form-urlencoded, spaces are to be replaced by +, so one may wish to follow a encodeURIComponent() replacement with an additional replacement of %20 with +.
Examples
Encoding for Content-Disposition and Link headers
The following example provides the special encoding required within UTF-8 {{HTTPHeader("Content-Disposition")}} and {{HTTPHeader("Link")}} server response header parameters (e.g., UTF-8 filenames):
Encoding for RFC3986
The more recent RFC3986 reserves !, ', (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the {{glossary("IPv6")}} URI syntax. An RFC3986-compliant encodeURI implementation should not escape them, which is demonstrated in the encodeURI() example.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("decodeURI()")}}
{{jsxref("encodeURI()")}}
{{jsxref("decodeURIComponent()")}}