Multi-line Strings in JavaScript

When diving into JavaScript, a frustration coders will run into is the apparent lack of support for multi-line string literals in Javascript. What does this mean? Well, say you have a lot of text that you wish to define as a string in JavaScript. Often, for code readability, you would like to set the value of the string using characters across multiple lines.

Unfortunately, you can’t just assign a string like:

var string = 'this is my
very long string';

There are, however, a couple of great ways to get around this. My favorite methods, personally, are the following.

Heredoc Method

var string = (<r><![CDATA[

   The text string goes here.  Since this is a XML CDATA section,
   stuff like <> work fine too, even if definitely invalid XML. 

]]></r>).toString();

The major advantage of using the heredoc method is it preserves whitespace, which is super userful! As you can imagine, it’s very easy to define tabs and other whitespace by actually entering that whitespace into your string. No need for “\t.”Backslash MethodAnother method includes using a backslashes to denote end of the line in the source. This will translate to a continuous line in JS.

Backslash Method

var string = "another long \
test string";

In this technique, the backslash acts as a line terminator, representing to the JavaScript engine that the string’s definition will continue on the next line. Note: after doing some research, this technique is apparently not in compliance with browser standards; however, it works out fine when tested across all major browsers.

Concatenate Method

Of course, the traditional technique is to concatenate multiple strings together on multiple lines using the “+” operator:

var string = "really long string"+
"another even longer string";