Long multi-line strings in JavaScript

The other day I needed to make some dynamic entries into a JavaScript object array. One of the values for these was a block of HTML code that needed to be output. The problem is that the blocks have new line characters in them, and setting them up with standard quotes (single or double) doesn’t work across multiple lines.

The way that I thought of doing this first was to try and replace all of the new line characters with a space. That would leave me a single line of text. That would work, but it’s a fair bit of processing, not to mention code, for something so simple.

So I did some research…

In newer versions of JavaScript, you can set up a multi-line string using backticks instead of quotes. Sound to simple to be true? Thankfully this time it’s not!

var my_string = `First Line
Second Line
Third Line`;

Of course, there’s compatibility issues with some older browsers, so if you need to support older versions this may not be for you. If you are lucky enough to not have to worry about older browsers, then this is definately the trick for you.

Leave a Reply

Your email address will not be published.