Difference between exhaust, encodeURI and encodeURIComponent

Asked

Viewed 1,387 times

10

What is the difference between these three functions, and when to use each of them?

  1. escape()
  2. encodeURI()
  3. encodeURIComponent()
  • 2

    You have an answer to this question in the English version https://stackoverflow.com/questions/75980/when-are-you-supposed-to-use-escape-instead-ofencodeuri-encodeuricomponent

1 answer

13


According to the MDN:

Function escape

Note: in accordance with Microsoft Docs and MDN the function escape is obsolete, encodeURI and encodeURIComponent in its place (depending on the need)

The hexadecimal form for characters, whose unit code value is 0xFF or less, it is a two-digit escape sequence: %xx. For characters with a larger unit of code, the four-digit format %uxxxx is used.

It will not escape the following characters:

@ * _ + - . /

Function encodeURIComponent

The function encodeURIComponent encodes a component "Uniform Resource Identifier" (URI), replacing each instance of certain characters with one, two, three or four escape sequences that represent the UTF-8 character encoding (only four escape sequences for characters composed of two "substitution characters").

It will not escape the following characters:

A-Z a-z 0-9 - _ . ! ~ * ' ( )

Function encodeURI

Does not encode characters that have a special meaning (reserved characters) for a URI. The following example shows all 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

That’s why encodeURI does not encode characters that are necessary to formulate a complete URI. In addition, it does not encode some additional characters, known as "non-reserved tags", that do not have a reserved purpose, but are allowed in a "as is" URI (see RFC2396)

It will not escape the following characters:

A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
  • 1

    When the period’s over, I’ll reward that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.