41

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

Anything better than this?

str = "line 1" +
      "line 2" +
      "line 3";
2
  • 3
    Surely the example in this question is more readable than the answer by @dreftymac no? Commented Jan 31, 2013 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. Commented Mar 6, 2013 at 22:50

9 Answers 9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This also makes it useful to do automatic linebreaks with the join character being \n. Very handy.
17

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

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

4 Comments

Yes - it's easier to understand at a glance.
this doesnt validate as well. I had once a script with some html like this and I had to redo it.
You had to escape the HTML, the way the string is constructed has nothing to do with validation.
JSHint and most other validation tools want the concatenation operator at the end of the lines.
13

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.

6 Comments

Wow. This really works. Thanks Gordon! I didn't know you could do this at all...
readable but not correct for js error parsers!
@Elzo Valugi "readable but not correct for js error parsers!" jslint doesn't validate it, but I use the error parser at javascriptlint.com, which does validate it.
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.
If you're using JSLint, you can use the multistr option so it validates with it!
|
11

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

1 Comment

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.
9
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")/

4 Comments

is this method still faster than the "str" + "str" concatenation alternative or does it not matter to today's browsers?
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 video.yahoo.com/watch/4141759/11157560 at 23:08
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 :)
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).
7

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.

1 Comment

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

2 Comments

As far as I remember, this does not work in some browsers. Presumably some version(s) of IE.
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.
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();

4 Comments

You don't need the XMLList literal (<>..</>). You can just do <![CDATA[..text..]]>.toString()
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 (?)
This is no longer supported in Firefox as of version 17. I don't believe ANY browsers support it now.
@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"
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.

1 Comment

This does now work in Firefox, and most recent browsers. See this answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.