RSS LinkedIn Twitter

Getting Strings from charCodes

March 31st, 2008 Categories: Actionscript, Flex 3, Languages

When handling KeyboardEvents in Actionscript, the event contains two important bits of data regarding the key that was pressed. One is the charCode, the other is the keyCode. In short the difference between the two is that one represents the character that was intended by the key, the other is the actual key that was pressed. For example, A and a are different characters (different charCodes) but they both come from pressing the same key (keyCode).

charCodes are good for a number of reasons, one of which is that the alphabetic characters are sequential when converted to charCodes, so if you needed to test whether the character entered fell into a range (alphabetic keys) it is convenient to have it expressed as a number.

I thought that getting the actual character typed in (easier conceptually when dealing with single keys) would be a fairly straight forward operation. It turns out that it is surprisingly easy, but it was more difficult wading through the documentation trying to find it. There’s a static variable-arity method on the String class that will perform the conversion: String.fromCharCode(charCode : uint). Here’s an example:

private function handleInput(event : KeyboardEvent) : void { String.fromCharCode( event.charCode) );

Because it is variable arity, you can also pass as many charCodes to the method as you want, and it will convert them all into a String. For example:

private function handleInput() : void { String.fromCharCode(97, 98, 99) );

will output:
It would also be a simple exercise to extend this method so that it could accept an Array of charCodes (if you needed to).


One Response to “Getting Strings from charCodes”

  1. Roshan
    November 16th, 2008 at 23:25

    hey thanks for the info…i was confused about this but now its clear..

Leave a Comment