Difference between escape, encodeuri, encodeURIComponent

escape()

Don’t use it, as it has been deprecated since ECMAScript v3.

encodeURI()

Use encodeURI when you want a working URL. Make this call:

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

Then you may create the URL you need:

Note that encodeURIComponent does not escape the ‘ character. A common bug is to use it to create html attributes such as href=’MyUrl’, which could suffer an injection bug. If you are constructing html from strings, either use ” instead of ‘ for attribute quotes, or add an extra layer of encoding (‘ can be encoded as %27).

Parctice

Below is the function for pre-populate email links with subject and body text via different email

It can automatically pre-populate the subject line, and the body of the message after clicked the link

Summary

From article Comparing escape(), encodeURI(), and encodeURIComponent()

1. The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

2. Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs [REF] as opposed to the querystring, which is part of a URL. Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURI() will not encode: ~!@#$&*()=:/,;?+'

3. Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() will not encode: ~!*()'

References

MSDN JScript Reference – escape(), encodeURI(), encodeURIComponent()

Mozilla Developer Core Javascript Guide – escape(), encodeURI(), encodeURIComponent()

ASCII Table – http://www.asciitable.com/

W3C’s URIs, URLs, and URNs: Clarifications and Recommendations 1.0 – http://www.w3.org/TR/uri-clarification/

Resource:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA