Path: blob/main/files/en-us/web/javascript/reference/global_objects/encodeuri/index.md
6529 views
------{{jsSidebar("Objects")}}
The encodeURI() 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("encodeURIComponent()")}}, this function encodes fewer characters, preserving those that are part of the URI syntax.
{{EmbedInteractiveExample("pages/js/globalprops-encodeuri.html")}}
Syntax
Parameters
uri: A string to be encoded as a URI.
Return value
A new string representing the provided string encoded as a URI.
Exceptions
{{jsxref("URIError")}}
: Thrown if
uricontains a lone surrogate.
Description
encodeURI() is a function property of the global object.
The encodeURI() function escapes characters by UTF-8 code units, with each octet encoded in the format %XX, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause encodeURI() to throw a {{jsxref("URIError")}}.
encodeURI() escapes all characters except:
The characters on the second line are characters that may be part of the URI syntax, and are only escaped by encodeURIComponent(). Both encodeURI() and encodeURIComponent() do not encode the characters -.!~*'(), known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See RFC2396)
The encodeURI() function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning:
Examples
encodeURI() vs. encodeURIComponent()
encodeURI() differs from {{jsxref("encodeURIComponent()")}} as follows:
Note that encodeURI() by itself cannot form proper HTTP {{HTTPMethod("GET")}} and {{HTTPMethod("POST")}} requests, such as for {{domxref("XMLHttpRequest")}}, because &, +, and = are not encoded, which are treated as special characters in GET and POST requests. encodeURIComponent(), however, does encode these characters.
Encoding a lone high surrogate throws
An {{jsxref("URIError")}} will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example:
Encoding for RFC3986
The more recent RFC3986 makes square brackets reserved (for {{glossary("IPv6")}}) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ', (, ), and *, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("decodeURI()")}}
{{jsxref("encodeURIComponent()")}}
{{jsxref("decodeURIComponent()")}}