9.14. Converting Between Strings and Unicode or ASCII


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


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


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

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?"; ...

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.