Encode decode and escape unescape characters

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:

    &amp; ? & (ampersand, U+0026)
    &lt; ? < (less-than sign, U+003C)
    &gt; ? > (greater-than sign, U+003E)
    &quot; ? " (quotation mark, U+0022)
    &apos; ? ' (apostrophe, U+0027)

To encode HTML characters in ActionScript use the encodeURI() method.

var value:String = encode("Ben & Jerry"); // value equals "Ben &amp; 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/?&amp;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.

You can read more about character encoding, HTML encoding and escape characters (this last article may not refer to this case here which in that case defer back to the character encoding article).

This entry was posted in Flex. Bookmark the permalink.

Leave a Reply

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

Wrap your code before posting! Click the links below:

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">