Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cleanest way to write a multiline string in JavaScript? [duplicate]

It doesn't really have to add newlines, just something readable.

Anything better than this?

str = "line 1" +       "line 2" +       "line 3"; 
like image 289
Robin Rodricks Avatar asked Oct 19 '09 15:10

Robin Rodricks


People also ask

How do I create a multiline string in JavaScript?

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.

What is multiline in JavaScript?

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.

Can we write multiple line in JS?

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.


1 Answers

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.

like image 195
dreftymac Avatar answered Oct 02 '22 12:10

dreftymac