Multi Line Strings: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
No edit summary
Replaced content with "Modern browsers (including Firefox since version 34) support [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals template literals] which..."
 
(5 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Sometimes, it is desirable to use a multi line string in JavaScript, such as when adding css styles.
Modern browsers (including Firefox since version 34) support [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals template literals] which can span lines.
Here are some approaches, and discussion about the strengths and weaknesses of each approach.
 
== Concatenation ==
 
The basic method:
 
<pre class='sample'>
var longString = "Lorem ipsum dolor sit amet, " +
  "venenatis penatibus etiam. " +
  "Nec purus cras elit nec. " +
  "Elit pharetra hymenaeos. " +
  "Donec at cubilia pulvinar elit. " +
  "Aliquet pretium tortor montes maecenas ante amet vel bibendum.";
</pre>
 
Pros:
* Simple to understand.
Cons:
* Extra syntax at the head and tail of every line.
* JavaScript string concatenation has poor performance characteristics.
 
A very similar but more efficient approach would define an array of many strings, then join them into one long string:
 
<pre class='sample'>
var longString = ["Lorem ipsum dolor sit amet, ",
  "venenatis penatibus etiam. ",
  "Nec purus cras elit nec. ",
  "Elit pharetra hymenaeos. ",
  "Donec at cubilia pulvinar elit. ",
  "Aliquet pretium tortor montes maecenas ante amet vel bibendum."
  ].join("");
</pre>
 
== Line continuation ==
 
JavaScript can continue lines, via trailing backslashes, like C:
 
<pre class='sample'>
var longString = "Lorem ipsum dolor sit amet, \
  venenatis penatibus etiam. \
  Nec purus cras elit nec. \
  Elit pharetra hymenaeos. \
  Donec at cubilia pulvinar elit. \
  Aliquet pretium tortor montes maecenas ante amet vel bibendum.";
</pre>
 
Pros:
* Efficient.
Cons:
* An uncommon technique, therefore not as well understood.
* Requires extra syntax, albeit not as much as with concatenation.


[[Category:Coding Tips:General]]
[[Category:Coding Tips:General]]

Latest revision as of 19:58, 3 November 2017

Modern browsers (including Firefox since version 34) support template literals which can span lines.