Multiline Strings in AS3

Posted in ActionScript 3
2009-03-28 19:30:51 +0000 UTC

If you've ever needed to make multiline strings in AS3, you may have found yourself doing something awkward like this:

var s:String = "This is a multiline string\\n";
s += "It has multiple lines.\\n";
s += "Too bad the implementation is weird.";

Here's a trick to create true multiline strings in AS3 code, useful for blocks of JavaScript used in ExternalInterface calls:

var js:String = ( <![CDATA[
Your string
]]> ).toString(); "function(){" + js + "}" );

What this does is create an XML object, using the tag wrapped in a set of parenthesis. Then the toString() method is called to cast as a string. This works because AS3 code allows for multiline XML code, but not strings.

Thanks for the tip, Doug!