50

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
  • 34,477
  • 60
  • 195
  • 309

2 Answers2

79

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?

nzifnab
  • 15,876
  • 3
  • 50
  • 65
  • no I want them visually be on the new lines in javascript... seems it's quite impossible – iLemming Oct 15 '13 at 19:18
  • 7
    @Agzam: Why do you care what the generated JavaScript looks like? That stuff is not intended for human consumption. – mu is too short Oct 15 '13 at 19:21
  • Yes, why does that matter? – nzifnab Oct 15 '13 at 19:22
  • I'm dealing with xml strings. Manually converting existed javascript code into coffee, and trying to compare results... And it's hard to compare – iLemming Oct 15 '13 at 20:52
  • 2
    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 http://js2coffee.org/. I'm not sure what any of this has to do with XML strings. – nzifnab Oct 15 '13 at 22:09
22

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.'