Flex/Flash/Actionscript

Multi-line strings in Actionscript 3

Jesus, this took me a bazillion hours to figure out.

OK, so I wanted to set a String variable in Actionscript. The actual value I wanted was a block of Javascript code (more on why in a second). In PHP we’re allowed to use something called heredoc syntax. So I could write my code like this:

$str = <<

and then my variable would contain the multi-line string with line breaks and all. Sweet, that's what I wanted to do. Turns out AS3 doesn't support heredoc syntax. So that sucks.

I spent the next few hours banging my head on a wall trying to figure out how to cut and paste my long block of code that I wanted to get into a String to work correctly in my AS code. Googling "actionscript heredoc" gave me nothing. Googling "actionscript multi-line string" gave me nothing. The golden nugget was finally realizing that AS3 is basically Javascript 2, so maybe some JS guys had figured this one out. Turns out they did. Here's the JS nugget that led me to my solution.

You can use the same method in Actionscript 3. So your AS code would look like:

private var myString:String = ( 

It's easier in MXML, in that case all you need to do is something like:


	

So that's how you simulate the heredoc syntax in AS3.

And a quick note: when I was trying to figure this out I was making a class that injected Javascript code into the HTML wrapper for a component to execute. See Abdul Qabiz's post here for a description of this method and a utility class to help you do this. Basically this let me write a component that used both Actionscript and Javascript and I could keep all my AS code and my JS code within the Actionscript component (as opposed to putting in the HTML wrapper). That's pretty frickin cool.

Standard

30 thoughts on “Multi-line strings in Actionscript 3

  1. woops, looks like wordpress stripped out the cdata part of your comment, email me and I’ll edit the comment and get the right code in there

  2. Its funny how the timing of posts happens sometimes. I’ve actually been working with the same basic thing the past few days, embedding a large chunk of VBA code in my Flex app (don’t ask), and went with an XML var defined in MXML. I think I like this approach better though, so thanks!

    PS – I’ll be attending your talk at 360|Flex, I’m looking forward to it.

  3. It works without quotation for me.
    It’s nice to do such thing:

    var injectScript:String =
    (
    <![CDATA[
    var e = document.createElement(“script”);
    void(e.setAttribute(“src”,”MiScript.js”));
    void(e.setAttribute(“type”,”text/javascript”));
    void(document.getElementsByTagName(“head”)[0].appendChild(e));
    ]]>
    ).toString();
    ExternalInterface.call( “function(){“+injectScript+”}” );

    I also hate modifying the html template…
    Thanx for sharing!
    😉

  4. Nice!!! I was abusing the textarea like so:

    <mx:TextArea id=”textarea1″ visible=”false”>
    <mx:text>
    <![CDATA[some stuff]]>
    </mx:text>
    </mx:TextArea>

    Having figured out the way to do heredoc style would you also know how to wrap a cdata tag around content in an xmlnode? For example:

    myXML.someNode = “<![CDATA[” + someXHMTL + “]]>”;

  5. Cool! I would try to use this technique in my JavaScript Inject code. I used some regex to strip/replace characters there..

    Thanks for sharing..

    -abdul

  6. I know this works in AS2, haven’t tried it in AS3:

    myString = “This is line number one.”
    myString += “\n”
    myString += “This is the next line.”

    Great code though from the looks of it. Haven’t had a chance to try it out, but thanks for sharing.

  7. Thanks Judah for getting me here. This looks promising but when I paste in Joan’s code snippet, I get parse error messages.

  8. I get those errors too but for all the code on this page. I’m using FB3 and I’m wondering if this will not work in it?

    private var injectScript:String = String( ).toString();

    Parse error at ‘ ).toString();\n\t\t’. FlashTerbate FlashTerbate.mxml line 21

  9. Tim says:

    Nice solution Doug!
    It’s a great technique when you’re wanting to dump a single block of HTML text into a Textfield and you don’t feel it justifies the use of its own XML file.

  10. Jason says:

    This has probably long been figured out, but I was looking for a solution to posting xhtml data from flex to a blog using XMLRPC. When I tried this solution, I was also getting the parse errors whenever I append the CDATA end tag as one string. So what I ended up having to do was:

    myBlogPost:String = ”;

    The parse errors stopped.

  11. Jason says:

    Um, oops, that would be:

    myBlogPost: String = ‘[envision the C-DATA start tag here]’ + blogBody.xhtmlText + ‘]’ +’]’ + ‘>’;

  12. Pingback: [ fla:pik ] Blog » Multi-line strings in Actionscript 3

  13. Damilola "Chayz" Jegede says:

    Hey Ya’ll. Very good stuff. My own area is trying to embed CSS in an as file. Wierd huh? Thanks Doug!

  14. Ah, excellent! I was storing level data for my game as large XML files and really wasn’t looking forward to removing all the newlines and pasting in thousands of characters of level data on a single, unreadable line. Bravo – worked like a charm and saved me pulling out some Excedrin! Thank you. 🙂

  15. In regards to Nur’s comment:
    I know this works in AS2, haven’t tried it in AS3:
    myString = “This is line number one.”
    myString += “\n”
    myString += “This is the next line.”
    —————————————————————-
    I used this for an Air 1.5 application I’m building in Flash CS4 with AS3 and it works just fine for me. I needed to reference variables (XML nodes) instead of just text and add this into items in a list component – found this solution to work perfectly. Short answer -> It worked in AS3 for me.

  16. Thanks! Took me a while to find this page but the solution works perfectly!

    I am embedding Processing code into Processing.as and compiling using the command line.

    Here’s my Actionscript code:

    private var script:String = ( <![CDATA[
    size(200, 200);
    smooth();
    background(0);
    strokeWeight(10);

    for(int i = 0; i < width; i++) {
    float r = random(255);
    float x = random(0, width);
    stroke(r, 100);
    line(i, 0, x, height);
    }
    ]]>).toString();

    Great stuff!

    Telmo

  17. Pingback: Understanding Flex » Blog Archive » a heredoc in Actionscript

  18. You can also do this:

    var x: String = “\
    hello \
    world \
    xyz”;

    Since the \ will escape the line terminator. I know it is not exactly the same but sometimes a little more lightweight than going for CDATA 🙂

  19. A simple solution for storing JavaScript in AS3 is to embed it as a class like so;

    [Embed(source = “jsFunctionInjection.js”, mimeType=”application/octet-stream”)]
    protected var MyJavascript:Class;

    You can then get the string version for injection by doing this;

    var js:String = new MyJavascript().toString();

    I’ve made a class that tests to see if jQuery is present, if not it injects it into the DOM, then executes a JavaScript function that utilises jQuery. Here’s a great source for all JavaScript injection (it’s 6 pages long but really worth it)

    http://bit.ly/12wcm

  20. Just a note of thanks. 4 years later, I Google for heredoc in Flex and voila. Try it to make sure the mx:HTML component will display some test documents correctly with a quick cut and paste into my sandbox/playground app and it’s wonderful.

    Thanks!

Comments are closed.