A couple weeks ago I needed to easily convert HTML entities in a string back to their normal representation, but I didn’t really find anything nice, and wound up just using str.replace(/&/g, "&").replace(/'/g, "'"); since those were the only characters I was having a problem with at the time.

But today I went searching again for something better, and found a really great way to escape and unescape HTML entities. Not sure why I didn’t find his post the first time, I guess my Google-fu was weak that day.

Anyway, I’ve wrapped his methods up in a little helper class, and it works great:

package com.grooveshark.utils
{

    public class HTMLEntityUtils
    {
        import flash.xml.XMLDocument;
        import flash.xml.XMLNode;
        import flash.xml.XMLNodeType;

        public function HTMLEntityUtils()
        {
        }

        public static function htmlEscape(str:String):String
        {
            return XML(new XMLNode(XMLNodeType.TEXT_NODE, str)).toXMLString();
        }

        public static function htmlUnescape(str:String):String
        {
            return new XMLDocument(str).firstChild.nodeValue;
        }
    }
}

Hope it helps someone else!

3 Responses to “HTML Entities and Actionscript”

  1. pcfan Says:

    Thanks a lot ! I was about to use some rope and soap to solve this problem ! :)

  2. ThingsDatDontWork Says:

    This does not work.

  3. RUNRUNRUN Says:

    Doesn’t work with many HTML entities such as “è”, “à”, “ê” and so on.
    A similar trick, using a TextField htmlText property doesn’t work better. AS3 only know a few HTML entities.

Leave a Reply