Reputation: 3413
Well i have a long string in double quotes
var Variable = "Really Long ...... String"
I would want to do this
var Variable = "Really
Long
......
String"
Currently I do this
var Variable = "Really\n\
Long\n\
......\n\
String"
It works correctly across all browsers. But is it the correct way to do it?
Upvotes: 1
Views: 1233
Reputation: 523164
The LineContinuation is a new feature in ECMA-262 5th edition (§7.8.4). If you absolutely must comply to ECMAScript 3, avoid it and use +
or .join('')
or whatever. But as you've mentioned, this particular feature is supported among major browsers (even IE 6)[1], I see no strong reason to avoid this other than having a coding convention.
(Ref: [1] http://shwup.blogspot.com/2009/05/line-continuation-in-javascript.html)
Upvotes: 0
Reputation: 32052
JavaScript does not support "here documents" as PHP does, so you can't do much better. You will end up with many spaces at the beginning of lines though (if you indent the code the way you present it here). To avoid that, use string concatenation:
var Variable = "Really\n" +
"Long\n" +
"String";
Or array joining (as suggested by meder):
var Variable = [
"Really",
"Long",
"String"
].join('\n');
Upvotes: 0
Reputation: 816242
You can use an array and join the values. But I am not sure about performance. If you use string concatenation, it can (and most likely will) be optimized by the engine (meaning it generates one string on parsing the code), but whether engines are so smart to discover a simple join with an array.... I don't think so.
var Variable = ["Really ",
"Long ",
"...... ",
"String"].join('');
Upvotes: 0
Reputation: 186552
I'd recommend just joining it.
var str = [
'This is a very long piece ',
'of string that I\'m going to join together ',
'right about now.'
].join('')
Upvotes: 1
Reputation: 10119
I think using the plus sign might be more effective.
var Variable = "Really " +
"Long " +
"...... " +
"String";
In your example above, how do you know how many spaces are before the word "Long", for example? I would not count on that being consistant across browsers.
My understanding is that using the plus sign to concatentate strings is just as efficient...javascript parsers are smart enough to handle that the same way as your example.
Upvotes: 4