coffeescript multiline strings compile into multiline strings

21,607

Solution 1

Try using the heredoc syntax:

myString = """
answer
to life
the universe
and everything
is
#{40+2}
"""

This converts to this javascript:

var myString;

myString = "answer\nto life\nthe universe\nand everything\nis\n" + (40 + 2);

There's not really any point to make it actually be on newlines in the compiled javascript visually, is there?

Solution 2

I agree it is nice to be able to keep your indentation when defining long strings. You can use string addition for this effect in coffeescript just like you can in javascript:

myVeryLongString = 'I can only fit fifty-nine characters into this string ' +
                   'without exceeding eighty characters on the line, so I use ' +
                   'string addition to make it a little nicer looking.'

evaluates to

'I can only fit fifty-nine characters into this string without exceeding eighty characters, so I use string addition to make it a little nicer looking.'
Share:
21,607
iLemming
Author by

iLemming

Updated on November 14, 2020

Comments

  • iLemming
    iLemming over 3 years

    How come that this string

    "answer 
     to life 
     the universe 
     and everything
     is
     #{40+2}
    "
    

    compiles into

    "  answer   to life   the universe   and everything  is  " + (40 + 2) + "";
    

    how can I force coffescript to keep it multiline (keeping string interpolation intact):

     "answer \ 
     to life \
     the universe \
     and everything \
     is \
     "+(40+2)
    
  • iLemming
    iLemming over 10 years
    no I want them visually be on the new lines in javascript... seems it's quite impossible
  • mu is too short
    mu is too short over 10 years
    @Agzam: Why do you care what the generated JavaScript looks like? That stuff is not intended for human consumption.
  • nzifnab
    nzifnab over 10 years
    Yes, why does that matter?
  • iLemming
    iLemming over 10 years
    I'm dealing with xml strings. Manually converting existed javascript code into coffee, and trying to compare results... And it's hard to compare
  • nzifnab
    nzifnab over 10 years
    When you convert javascript to coffeescript the resulting compiled js will almost NEVER look the same - trying to diff them is an exercise in futility. Also copying the js verbatim into coffeescript usually just results in crappy coffeescript. You can usually do things much more elegantly with coffee. If you really want to convert your legacy js to coffee en-masse (and don't want to just write it with 'proper' coffeescript techniques) you can use a tool like js2coffee.org. I'm not sure what any of this has to do with XML strings.