O'Reilly logo

Actionscript Cookbook by Joey Lott

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

9.14. Converting Between Strings and Unicode or ASCII

Problem

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

Solution

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

Discussion

You can use fromCharCode( ) to display characters that you cannot enter into your Flash document directly. The method is a static method, which means that it is invoked from the top-level String object instead of from a string instance. For values less than 128, fromCharCode( ) essentially converts a numeric ASCII code to its equivalent character.

/* Outputs:
   New paragraph: ¶
   Cents: ¢
   Name: Joey
*/
trace("New paragraph: " + String.fromCharCode(182));
trace("Cents: " + String.fromCharCode(162));
trace("Name: " + String.fromCharCode(74, 111, 101, 121));

You can use the charCodeAt( ) method 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( ) essentially converts a character to its equivalent ASCII code.

myString = "abcd";

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

The fromCharCode( ) method is an alternative to using Unicode escape sequences to display special characters. However, you can also use fromCharCode( ) in concert with charCodeAt( ) to test for the existence of special characters:

myString = String.fromCharCode(191) + "Donde es el ba" + String.fromCharCode(241) + "o?"; ...

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