Wednesday, May 30, 2007

encode, encodeURI, encodeURIComponent - When to use which?

(Full explanation at http://xkr.us/articles/javascript/encode-compare/)
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: @*/+

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: ~!@#$&*()=:/,;?+

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: ~!*()'

No comments: