What's the difference between these three functions, and when to use each one of them?
escape()
encodeURI()
encodeURIComponent()
What's the difference between these three functions, and when to use each one of them?
escape()
encodeURI()
encodeURIComponent()
According to the MDN:
escape
Note: as Microsoft Docs and MDN / a> function
escape
is deprecated,encodeURI
andencodeURIComponent
instead (depending on need)
The hexadecimal form for characters, whose code unit value is 0xFF
or less, is a two-digit escape sequence: %xx
. For characters with a larger code unit, the four-digit format %uxxxx
is used.
It will not escape the following characters:
@ * _ + - . /
encodeURIComponent
The encodeURIComponent
function encodes a Uniform Resource Identifier (URI) component, replacing each instance of certain characters with one, two, three, or four escape sequences that represent UTF- 8 characters (there will only be four escape sequences for characters composed of two "replacement" characters).
It will not escape the following characters:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
encodeURI
Does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a "URI Scheme" can contain. Note how certain characters are used to mean special meaning:
http://username:[email protected]:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
So encodeURI
does not encode characters that are required to formulate a complete URI. In addition, it does not encode some additional characters, known as "non-reserved tags," which do not have a reserved purpose, but are allowed in a "as is" URI (see the RFC2396 )
It will not escape the following characters:
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #