40

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

Anything better than this?

str = "line 1" +
      "line 2" +
      "line 3";
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • 2
    Surely the example in this question is more readable than the answer by @dreftymac no? – Jasdeep Khalsa Jan 31 '13 at 18:02
  • Greetings @jasdeepkhalsa. There are two ways to look at it. The above example is definitely readable by virtue of having fewer characters. The problem comes when you have to *interact* with the code, by adding or removing lines or changing the order of the lines. The dreftymac example contains more characters, but it is much easier to interact with the code without accidentally triggering a syntax error. – dreftymac Mar 06 '13 at 22:50

9 Answers9

23

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
17

I like this version (different than yours just in formatting of the code):

var str = "line 1"
        + "line 2"
        + "line 3";
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
14

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.

Gordon Tucker
  • 6,653
  • 3
  • 27
  • 41
  • Wow. This really works. Thanks Gordon! I didn't know you could do this at all... – Robert Koritnik Oct 19 '09 at 15:12
  • 2
    readable but not correct for js error parsers! – Elzo Valugi Oct 19 '09 at 15:15
  • @Thomas: "In every example I've seen, you also put a \ after line3." Just bc the article you linked to had a typo does not mean it's right. read the rest of your article, he only did it once, in the first example. – geowa4 Oct 19 '09 at 15:22
  • 1
    @Elzo Valugi "readable but not correct for js error parsers!" jslint doesn't validate it, but I use the error parser at http://www.javascriptlint.com, which does validate it. – Gordon Tucker Oct 19 '09 at 16:04
  • 1
    This notation is not part of the official ECMA standard, but every major JS engine has supported it for years. However, you may run into trouble with JS compressors, syntax highlighters, etc. etc. – user123444555621 Oct 19 '09 at 17:37
  • 1
    If you're using JSLint, you can use the `multistr` option so it validates with it! – Jasdeep Khalsa Jan 31 '13 at 18:01
12

FYI. The way you suggest it is the correct way and better than the other answers. JsLint only validates your version.

Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
  • 7
    Tip: keep those lines short. If they stretch off the screen, you don't see the + and it gets unreadable. Or put the + at the beginning of the lines like Ionut suggests. – Nathan Long Oct 19 '09 at 18:13
10
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")/

NickFitz
  • 34,537
  • 8
  • 43
  • 40
  • is this method still faster than the "str" + "str" concatenation alternative or does it not matter to today's browsers? – Ty W Oct 19 '09 at 17:16
  • join is faster if you have maaaaaaaaaany parts to concatenate, because "+" will be executed (n-1) times, creating temporary results in each step. For details see http://video.yahoo.com/watch/4141759/11157560 at 23:08 – user123444555621 Oct 19 '09 at 17:27
  • 2
    We had a script that build the entire page through "str" + "str" and it was pretty slow (about 30 sec page load). We changed to use an array based appending system like this and it dropped to less than one second. So, yes, it is faster :) – Gordon Tucker Oct 19 '09 at 21:00
  • For what it's worth, in at least some modern browsers + is faster than the join() call there, especially if this code runs more than once (because the + on constant strings is constant-folded into a single string at parse time). – Boris Zbarsky Apr 23 '11 at 06:28
8

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.

Dean J
  • 39,360
  • 16
  • 67
  • 93
  • 1
    Too bad it is not allowed to vote more than once. This is THE definitive solution to losing energy and time over disputes for the "One Right Way™" to do things (so common in our industry). – dreftymac Sep 20 '12 at 18:13
2

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.

Community
  • 1
  • 1
Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
  • 1
    As far as I remember, this does not work in some browsers. Presumably some version(s) of IE. – Ionuț G. Stan Oct 19 '09 at 15:13
  • Ionut: Yes, you would need to test it in all browsers you are concerned with, and if it were to fail in a browser, I would suspect it would be IE. But I tested this in Firefox and it works there. – Thomas Owens Oct 19 '09 at 15:23
2

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();
user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • You don't need the XMLList literal (`<>..>`). You can just do `<![CDATA[..text..]]>.toString()` – Eli Grey Oct 19 '09 at 19:15
  • 1
    Have you tested? For some reason it doesn't work in Firefox. According to the standard, an XMLCDATA section is XMLMarkup, thus is an XMLInitialiser, which should be recognized by the engine as a PrimaryExpression (?) – user123444555621 Oct 26 '09 at 12:37
  • 1
    This is no longer supported in Firefox as of version 17. I don't believe ANY browsers support it now. – Brock Adams Jun 02 '13 at 01:46
  • @BrockAdams Thanks for pointing out. I think they did the right thing. Have to agree with Brendan Eich that [E4X "is a full of botches" and "crazyland objects"](https://bugzilla.mozilla.org/show_bug.cgi?id=560101#c9) – user123444555621 Jun 02 '13 at 08:41
1

Here's one that may be helpful during development when using Chrome.

function FSTR(f) {
    // remove up to comment start and trailing spaces and one newline
    s = f.toString().replace(/^.*\/\* *\r?\n/,"");
    // remove the trailing */} with preceeding spaces and newline
    s = s.replace(/\n *\*\/\s*\}\s*$/,"")
    return s;
}

s = FSTR(function(){/*
uniform vec2 resolution;
uniform float time;

void main(void)
{
    vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;
    vec2 cc = vec2( cos(.25*time), sin(.25*time*1.423) );
    ...
    float color = sqrt(sqrt(dmin))*0.7;
    gl_FragColor = vec4(color,color,color,1.0);
}
*/});

This does not work for Firefox, although it works in Chrome.

Example use would be for writing/testing webgl shaders. During development this is much nicer to work with and later you can always run over this with a simple regexp that converts that syntax into a cross-browser version.

Egon
  • 1,705
  • 18
  • 32
  • This does now work in Firefox, and most recent browsers. See [this answer](http://stackoverflow.com/a/5571069/331508). – Brock Adams Jun 02 '13 at 01:48