November 2nd, 2007
Converting html entities in AS3
Posted by
Ash in
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;
}
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();
}
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
trace(htmlEscape(“ham & eggs”)); // ham & eggs
trace(htmlUnescape(“ham & eggs”)); // ham & eggs

I don’t actually need to know this right now, but I will in about a week or so. Thanks m8.
Exactly what the doctor ordered. Thank you.
thanks!
Thank you!
This doesn’t when your string contains “<” characters, any ideas?
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,”<”).replace(/>/g,”>”)
Yes, that’s true, they don’t belong there. Thanks for your insight!
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();
}