It doesn't really have to add newlines, just something readable.
Anything better than this?
str = "line 1" + "line 2" + "line 3";
There are three ways to create a multiline string in JavaScript. We can use the concatenation operator, a new line character (\n), and template literals. Template literals were introduced in ES6. They also let you add the contents of a variable into a string.
This is a long message that spans across multiple lines in the code. In the above example, a multiline string is created using the + operator and \n . The escape character \n is used to break the line.
You can have multiline strings in pure JavaScript. This method is based on the serialization of functions, which is defined to be implementation-dependent. It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With