Search code examples
javascriptstringreadabilitymaintainability

What's the cleanest way to write a multiline string in JavaScript?


It doesn't really have to add newlines, just something readable.

Anything better than this?

str = "line 1" +
      "line 2" +
      "line 3";

Solution

  • Almost identical to NickFitz's answer:

    var str = [""
        ,"line 1"
        ,"line 2"
        ,"line 3"
    ].join("");
    // str will contain "line1line2line3"
    

    The difference, the code is slightly more maintainable because the lines can be re-ordered without regard to where the commas are. No syntax errors.