Razorberry’s Adobe Flash Blog

November 2nd, 2007

Converting html entities in AS3

Posted by Ash in Actionscript
Actionscript

I’m posting this here mainly because I always have to look it up. But maybe this post will help someone down the road.

Converting a string with html entities (such as &) to their respective symbols:

AS:


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

Converting a string so that it has html entities:

AS:


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


trace(htmlEscape(“ham & eggs”))// ham & eggs
trace(htmlUnescape(“ham & eggs”))// ham & eggs

8 Responses to ' Converting html entities in AS3 '

Subscribe to comments with RSS

  1. Patrick Burt said,
    on November 8th, 2007 at 1:35 pm

    I don’t actually need to know this right now, but I will in about a week or so. Thanks m8. :)

  2. bobnik said,
    on January 29th, 2008 at 11:49 pm

    Exactly what the doctor ordered. Thank you.

  3. bob said,
    on March 21st, 2008 at 5:20 pm

    thanks! :mrgreen:

  4. Diabolo said,
    on April 2nd, 2008 at 10:50 am

    Thank you!

  5. Monokai said,
    on April 23rd, 2008 at 8:06 am

    This doesn’t when your string contains “<” characters, any ideas?

  6. Ash said,
    on April 23rd, 2008 at 4:36 pm

    Monokai: Technically the htmlUnescape function shouldnt work for strings with < and > in, since those characters arent valid inside an escaped string anyway.
    However, you can replace those manually:
    str = str.replace(/</g,”&lt;”).replace(/>/g,”&gt;”)

  7. Monokai said,
    on April 25th, 2008 at 9:46 am

    Yes, that’s true, they don’t belong there. Thanks for your insight!

  8. Bevan said,
    on August 28th, 2008 at 5:05 am

    Thanks for posting.
    I did come across one little problem when using Air, if you pass in a null string it crashes Air (the ADL when debugging).
    So I made a small change:

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

Leave a reply

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad:

Macromedia XML News Aggregator