3
redditFunny = """
                                     TEST TEST
"""
console.log redditFunny

compiles into

var redditFunny;

redditFunny = "TEST TEST";

console.log(redditFunny);

I just want to output it as is

Jason
  • 71
  • 5

1 Answers1

2

From the fine manual:

Block strings can be used to hold formatted or indentation-sensitive text (or, if you just don't feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.

Emphasis mine. The example they give is that this CoffeeScript:

html = """
       <strong>
         cup of coffeescript
       </strong>
       """

becomes this JavaScript:

html = "<strong>\n  cup of coffeescript\n</strong>";

Note that the "inner" indentation is preserved while the "outer" indentation is removed.

The trick is to make CoffeeScript think you have a zero length "outer" indentation so that it will strip off zero leading spaces. Something like this chicanery for example:

s = """
\ this
 is indented
"""

will become this JavaScript:

s = "\ this\n is indented"
//   ^^      ^

Note that '\ ' is a complicated way of writing ' ' because an escaped space is just a space.

You could also use the fact that \u0020 is the Unicode escape for a space and say:

s = """
\u0020this
 is indented
"""

to achieve the same output.

This seems a bit dodgy and fragile to me but similar things are the recommended way to deal with leading #s in block regexes so this should be pretty safe.

I would probably avoid all this cleverness and write a little indenting function that split a string on '\n' and pasted it back together with leading indentation so that I could say:

indent(some_string_with_newlines, '           ')

to indent the block with eleven spaces.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • yeah it just seems really silly that there isn't a way to write a string without the indentation check. At the time of writing this I couldn't bring myself to write a function. guess that is the only way :( – Jason Mar 31 '15 at 15:37