Definition and Usage
The encodeURI()
function encodes an entire URL, except for special characters that are used to define its structure.
It is primarily used to encode entire URL strings.
Features
- Special characters with specific meanings in a URL, such as protocol, domain, and path delimiters (
/
,:
,?
,&
,#
), are not encoded. - Therefore, this function is suitable when the URL structure needs to be preserved.
- It is appropriate for encoding an entire URL,
- but not suitable for encoding individual URL components such as protocol, domain, path, or query values. In such cases, the
encodeURIComponent()
function should be used.
Note:
The encodeURI()
function is designed to encode a full URL while preserving its structure, leaving characters like /
, :
, ?
, &
, and #
intact. However, encoding individual URL components that contain these characters can cause issues. For example, if a path segment includes an &
, it might be mistaken for a query separator. In such cases, the encodeURIComponent()
function, which performs thorough encoding, should be used.
Basic Example
const uri = "https://www.example.com/?x=Sample Value";
const encoded = encodeURI(uri);
console.log(encoded);
// Output: "https://www.example.com/?x=Sample%20Value"
The encodeURI()
function has the following syntax:
Syntax
encodeURI(uri);
Parameters
uri |
The complete URL to encode. This function encodes the URL except for certain special characters within its components. |
---|
Return value
Returns a new string representing the encoded URI.
Characters Not Encoded by encodeURI()
- Alphabetic characters (A–Z, a–z)
- Digits (0–9)
;
,
/
?
:
@
&
=
+
$
-
_
.
!
~
*
'
(
)
#
Any other characters not listed here (including spaces) are encoded as a percent sign (%
) followed by the character's Unicode value in hexadecimal.
Example
const uri = "https://example.com/search?query=Hello, world!&page=1";
const encodedUri = encodeURI(uri);
console.log(encodedUri);
// Output: "https://example.com/search?query=Hello,%20world!&page=1"
In this example, the encodeURI()
function encodes the URI stored in the uri
variable. Characters that are not encoded include :
, /
, ?
, &
, =
, and !
.
Important Note
Using encodeURI()
alone cannot form valid HTTP GET or POST requests, such as those made with XMLHttpRequest
. This is because characters like &
, +
, and =
are not encoded and can be interpreted as special characters in GET and POST requests. In contrast, the encodeURIComponent()
function encodes these characters.
Specifications
Specification | |
---|---|
encodeURI()
|
ECMAScript Language Specification #sec-encodeuri-uri |
Browser compatibility
Function |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
encodeURI()
|
1 | 12 | 1 | 1.1 |