Search code examples
flashapache-flexactionscript

How do I use < or > inside of htmlText in actionscript?


I'm using font tags to set color of text inside of a TextArea in a Flex component. If the text between the html tags has a < or > then it breaks the text and doesn't render.

Here is an example of what I'm trying to do.

var textValue:String = "<some text>";
var myText:String = "<font color='#eeeeee'>" +  textValue + "</font>"
var textArea:TextArea = new TextArea();
textArea.htmlText = myText;

I've tried using the escape(textValue); function in Actionscript but all that does is encode the < > into the html values and it doesn't display them as they should in the HTML text.

I'm wondering if there is a way I can escape the < > so that the html will render it.


Solution

  • Thanks to some suggestions from @s9tpepper and @mike_robbo on twitter I was actually able to use the following code to encode characters the way flash HTML likes it.

            /**
             * Encode HTML.
             */
            public static function htmlEncode(s:String):String
            {
                s = s.replace("&", "&amp;");
                s = s.replace(" ", "&nbsp;");
                s = s.replace("<", "&lt;");
                s = s.replace(">", "&gt;");
                s = s.replace("™", '&trade;');
                s = s.replace("®", '&reg;');
                s = s.replace("©", '&copy;');
                s = s.replace("€", "&euro;");
                s = s.replace("£", "&pound;");
                s = s.replace("—", "&mdash;");
                s = s.replace("–", "&ndash;");
                s = s.replace("…", "&hellip;");
                s = s.replace("†", "&dagger;");
                s = s.replace("·", "&middot;");
                s = s.replace("µ", "&micro;");
                s = s.replace("«", "&laquo;");
                s = s.replace("»", "&raquo;");
                s = s.replace("•", "&bull;");
                s = s.replace("°", "&deg;");
                s = s.replace('"', "&quot;");
                return s;
            }