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!

6 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.

  4. Kawika Says:

    Thanks! This will make my life easier!

  5. Dud Says:

    thanks very-very-very-very much!!!!!!!!!
    i don’t know if now a days there is a better solution to encode or decode ascii characters or special characters found in html code, but this still works GREAT!
    I have an xml file: if loaded like so:

    works, but if placed in a webserver and loaded through an HTTPService did not translate the characters like ‘ (#039).
    After 2 days of desperate googling i finally landed here and got the solution.
    Thanks again!

  6. Clarine Cantrall Says:

    Each day I buy up and appearance from the Forbes listing of the richest us residents. If I’m not really there, Time passes to be effective.
    There is no time for cut-and-dried monotony. There’s time for work. And time for love. That leaves hardly any other time!

Leave a Reply