It doesn't really have to add newlines, just something readable.
Anything better than this?
str = "line 1" +
"line 2" +
"line 3";
It doesn't really have to add newlines, just something readable.
Anything better than this?
str = "line 1" +
"line 2" +
"line 3";
You could do
str = "\
line 1\
line 2\
line 3";
As mentioned in the comments, javascript parsers handle this fine (it works in all major browsers), but is not officially part of ECMA Script syntax. As such it may or may not work with compressors, error checkers, and isn't guaranteed to work in browsers.
This may be more readable, but isn't the 'best' way to do it. Maybe ECMA script will support something like c#'s @"" someday.
Yes! You can use the \ character to have JavaScript ignore end of line characters.
str = 'line 1 \
line 2 \
line 3';
However, as pointed out by Elzo Valugi, this will not validate using JSLint.
FYI. The way you suggest it is the correct way and better than the other answers. JsLint only validates your version.
Consistently.
Whichever way you choose, do it exactly the same way throughout your application. If you're working on an application that already has code written, accept the convention they set and go with it.
I like this version (different than yours just in formatting of the code):
var str = "line 1"
+ "line 2"
+ "line 3";
var str = [
"line 1",
"line 2",
"line 3"
].join("");
// str will contain "line1line2line3"
If you actually want newlines in the string, then replace .join("")
with .join("\n")
/
This will only work in browsers with E4X support - I wish we could use it in IE
var str = <><![CDATA[
Look, a multi-line
string! < " // ' ? &
]]></>.toString();
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.