JavaScript Reference ยท Global Functions and Values
The encodeURI() function
Reference for encodeURI(): percent-encoding a complete URL while keeping its structure, which characters are left alone, and when to use encodeURIComponent().
encodeURI() percent-encodes a complete URL so that unsafe characters such as spaces and non-ASCII letters become valid escapes, while the characters that give a URL its structure stay untouched. The :, /, ?, #, & and = all survive, so the result is still a working address.
It is meant for a URL you already have in one piece, for example one containing a space in its path. For individual values, use encodeURIComponent().
encodeURI("https://example.com/my page?q=cafรฉ"); // "https://example.com/my%20page?q=caf%C3%A9"
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
encodeURI(uri)
| Name | Description |
|---|---|
uri |
The complete URL to encode. Non-strings are converted to strings first. |
Return value: a new string where every character outside the allowed set is replaced by the percent-escapes of its UTF-8 bytes.
Exceptions: a URIError if the string contains a lone surrogate.
Usage notes
- Left unescaped: letters, digits,
- _ . ! ~ * ' ( )and the reserved characters; , / ? : @ & = + $ #. - Still escaped: spaces, quotes (
"),<,>,[,],{,},|,\,^, backticks and%. A%is always escaped, so already-encoded text becomes%25...(double encoding). - Not suitable for values. If a value contains
&,=,#or+,encodeURI()leaves them alone and the URL breaks. UseencodeURIComponent()for each value. - Encode once. Run it only on text that is not already percent-encoded.
- Square brackets in IPv6 hosts (
http://[::1]/) are escaped too, which makes such URLs invalid; avoid it for them. - Modern alternative:
new URL(text).hrefnormalizes and encodes a URL according to the URL standard, and throws for invalid input.
Browser support
encodeURI() is available in every browser and runtime.
Related
decodeURI(),encodeURIComponent(),URL- Lessons: Strings, Fetch