Search Flex Samples

Finding out a characters Unicode character code

Have you ever needed to know a character’s Unicode character code and had to spend minutes (or hours) looking it up? Well, here’s a little trick I learnt recently. ActionScript 3.0 (and ActionScript 2.0) have a handy little charCodeAt() method in the String class which takes a numeric parameter which specifies the desired character index in a string, and returns the numeric Unicode character code for that index. A poor explanation, I know, so lets take a look at some code


Not entirely interesting. Basically you define a string (in this case I just use an inline string rather than create a new temporary variable of String type) and then call the charCodeAt() method to convert that string into a number. The charCodeAt() method actually takes a single parameter, which, according to the documentation is:

An integer that specifies the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length - 1.

If you don’t pass in any value, the index value defaults to zero, which is the first character in the string. Bingo!

Now that you’re all suitably underwhelmed, lets look at another example…





<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="white" >



<mx:Script>

<![CDATA[

[Bindable]

private var charCode:Number = "&".charCodeAt();

]]>

</mx:Script>



<mx:Label text="@ = {'@'.charCodeAt()}" />

<mx:Label text="&amp; = {charCode}" />



</mx:Application>



<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

backgroundColor="white">



<mx:Script>

<![CDATA[

import mx.controls.dataGridClasses.DataGridColumn;

import mx.collections.ArrayCollection;



[Bindable]

private var arrColl:ArrayCollection;



private function doChange():void {

var letterArray:Array = textInput.text.split("");

arrColl = new ArrayCollection(letterArray);

dg.validateNow();

dg.selectedIndex = arrColl.length;

dg.scrollToIndex(arrColl.length);

}



private function CharCode(item:Object, column:DataGridColumn):String {

return item.charCodeAt().toString();

}

]]>

</mx:Script>



<mx:TextInput id="textInput" change="doChange();" width="100%" />

<mx:DataGrid id="dg" dataProvider="{arrColl}" width="100%" height="100%">

<mx:columns>

<mx:DataGridColumn headerText="Character" dataField="letter" />

<mx:DataGridColumn headerText="Char Code" labelFunction="CharCode" />

</mx:columns>

</mx:DataGrid>

<mx:Label id="lbl" />



</mx:Application>

0 comments:

Related Flex Samples

Learn Flex: Flex Samples | Flex Video Tutorials Flex Examples