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?"; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access