O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Converting Between Strings and Unicode or ASCII

Problem

You want to convert between characters and their corresponding Unicode code point (a.k.a. character code). Or you want to convert strings to and from ASCII codes.

Solution

Use the String.charCodeAt() and String.fromCharCode() methods.

Discussion

You can use fromCharCode() to display characters you cannot directly enter into your Flash document. The method is a static method, which means that it is invoked from the top-level String object instead of from a string instance. It takes an integer or a series of integers and coverts the character codes to their string equivalents. When values less than 128 are used, fromCharCode() essentially converts a numeric ASCII code to its equivalent character:

/* Displays:
   New paragraph: ¶
   Cents: ¢
   Name: Darron
*/
trace( "New paragraph: " + String.fromCharCode( 182 ) );
trace( "Cents: " + String.fromCharCode( 162 ) );
trace( "Name: " + String.fromCharCode( 68, 97, 114, 114, 111, 110 ) );

The charCodeAt() method can be used to retrieve the code point of the character at a particular index of a string. For characters whose Unicode code point is less than 128, charCodeAt() converts a character to its equivalent ASCII code:

var example:String = "abcd";

// Outputs the code point, 97, of the first character, a.
trace( example.charCodeAt( 0 ) );

The fromCharCode() method is an alternative to using Unicode escape sequences to display special characters. However, you can also use fromCharCode() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required