Multi-line strings in JavaScript

When programming with JavaScript, you often stumble over the missing possibility to realize multi-line strings by entering them in the code. While the task is no problem in other languages such as PHP or Ruby, JavaScript can only be solved with workarounds, the use of which depends on personal taste and browser support.


The obvious attempt

var str = "Dies ist eine
mehrzeilige
Zeichenkette.";

fails and the parser then complains about several things (in the form of unexpected token ILLEGAL), because JavaScript (in contrast to other programming languages ​​such as PHP) automatically inserts a semicolon after the end of each line:

var str = "Dies ist eine;
mehrzeilige;
Zeichenkette.";

A first solution to the problem consists of the simple string concatenation through the \ n and + operator:

var str = "Dies ist eine\n" +
"mehrzeilige\n" +
"Zeichenkette.";

If you prefer a less slow and more beautiful variant, add a backslash at the end of each line:

var str = "Dies ist eine\n\
mehrzeilige\n\
Zeichenkette";

Alternatively, you can also use the Join method and get:

var str = ["Dies ist eine",
"mehrzeilige",
"Zeichenkette"].join("\n");

On the other hand, if you get glowing eyes with regular expressions, use the following syntax (match() filters the values between the comments):

var str = (function () {/*Dies ist eine
mehrzeilige
Zeichenkette*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

Important: If the code is minified, this solution can be forgotten (since the comments are also removed).

The most beautiful variant is achieved with ECMA6 and the help of template strings:

var str = `Dies ist eine
mehrzeilige
Zeichenkette`;
Back