It is often confusing to know when and where to use encode and decode and escape and unescape. This post should give you some initial guidance in the context of it’s use in ActionScript and the Flash and AIR virtual machines.
Encode & Decode
When transmitting or storing text (characters) it is often necessary to encode or decode certain characters in the text to help retrieve or restore the text in it’s original meaning. This is the case in HTML and XML where certain characters such as the less than sign “<" and greater than sign ">” have an additional meaning in the context of the document.
In XML there are only five predefined character entity references. These are used to escape characters that are markup sensitive in certain contexts:
& ? & (ampersand, U+0026) < ? < (less-than sign, U+003C) > ? > (greater-than sign, U+003E) " ? " (quotation mark, U+0022) ' ? ' (apostrophe, U+0027)
To encode HTML characters in ActionScript use the encodeURI() method.
var value:String = encode("Ben & Jerry"); // value equals "Ben & Jerry";
If you are creating an XML file and you get an error similar to the following you will need to encode the characters manually.
Problem parsing external XML: sites.xml - (line 134) The reference to entity "q" must end with the ';' delimiter.
The first line generates this error while the second does not:
<item name="Google" url="http://www.google.com/?&q=" /> <item name="Google" url="http://www.google.com/?&q=" />
To decode the value in ActionScript use the decodeURI() method.
Note: When you work with XML in ActionScript code the encoding and decoding is sometimes taken care of for you by certain native XML methods. Examples are available online (possibly on this site).
Escape and Unescape
In the context of setting the content of a URL string you may need to convert some characters of it to ensure the browser can resolve it’s path.
The escape method converts the parameter to a string and encodes it in a URL-encoded format, where most nonalphanumeric characters are replaced with % hexadecimal sequences. When used in a URL-encoded string, the percentage symbol (%) is used to introduce escape characters, and is not equivalent to the modulo operator (%).
To unescape an escaped value in ActionScript use the unescape() method.