O'Reilly

Multi-Line JavaScript Strings

By on  

The JavaScript language performs automatic semicolon insertion at the end lines, so creating multiline strings usually ends up looking something like this:

var multiStr = "This is the first line" + 
	"This is the second line" + 
	"This is more...";

String upon string of concatenated JavaScript mess...ugly, slow, and ...ugly.  Many novice JavaScript developers don't know that there's a better way to create multiline strings:

var multiStr = "This is the first line \
	This is the second line \
	This is more...";

Adding a backslash at the end of each line tells the JavaScript engine that the string will continue to the next line, thus avoiding the automatic semicolon insertion annoyance. Note that the second string includes line breaks within the string itself.  Just another nice tip to add to your JavaScript arsenal!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Regular Expressions for the Rest of Us

    Sooner or later you’ll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome,...

Incredible Demos

  • Detect DOM Node Insertions with JavaScript and CSS Animations

    I work with an awesome cast of developers at Mozilla, and one of them in Daniel Buchner. Daniel's shared with me an awesome strategy for detecting when nodes have been injected into a parent node without using the deprecated DOM Events API....

  • Pure CSS Slide Up and Slide Down

    If I can avoid using JavaScript for element animations, I'm incredibly happy and driven to do so.  They're more efficient, don't require a JavaScript framework to manage steps, and they're more elegant.  One effect that is difficult to nail down with pure CSS is sliding up...

Discussion

  1. Matt Titchener

    It should be noted the backslash multiline string notation is not part of any ECMAScript standards and can break various minifiers. Otherwise, it’s definitely good to know!

  2. I think this is quite controversial. Other than issue with minifiers, ‘backslashes’ can cause error if there is any white space after it. I often write multiline string as arrays and join, this way IMO is quite readable.

    var multiStr = [
    "This is the first line",
    "This is the second line",
    "This is more..."
    ].join("\n");

    You can also see the intent here wether it’s about construct a real multiline string (with join(“\n”)) or just try to avoid writing a long string (with join(“”)).

  3. /**
    * @tungd : +1
    *
    * Moreover, you can't indent your code or it will add the whitespaces to the string.
    *
    * e.g:
    **/

    "my string \
    is long" === "my string is long"; // and not "my string is long"

  4. See also this performance test from different possibilities; the \ variant is the fastest.

  5. I forgot about this implementation till this morning while I was working on some jQuery forms. Funny I came across this now.

  6. While I understand the concern for minifiers, we don’t write JS for minifiers, we write JS for JS interpreters. JS minifiers need to improve. If the minifier you use doesn’t support this basic pattern, however, feel free to work around it.

  7. Jamie

    When I first found out that you could escape newlines, I thought it was a pretty neat way to split a single line of text over several lines. It’s advantages are that it’s faster than concatenation and more readable than having the text spanning one long line that you have to scroll through.

    However, it’s slower, less readable and less maintainable than having the text on one line and just turning on word wrap in your IDE. It’s also error prone, for reasons explained above.

    The most common reason for including large, unbroken chunks of text in a JavaScript file is for the purposes of HTML injection, in which case I would personally include the text in a separate tag, which I then retrieve with innerText and store in a variable. That way, I can format it as HTML, but it won’t get shown on the page, nor get interpreted as JavaScript. Yes, it’s slower, but it’s much more readable and maintainable.

  8. Arian Stolwijk

    You can just use the first one, minifiers (at least uglify-js) will change the var a = "foo" + "bar"; into var a = "foobar"; anyway.

  9. In Google javascript guide, they advise “”+ instead of \ because . «The whitespace at the beginning of each line can’t be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript.»

    http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml?showone=Multiline_string_literals#Multiline_string_literals

    What do you think? Could you please enlighten me?

    Thank you.

  10. Joe T.

    @David: i don’t think there’s much case for “improving” minifiers to support the escaped line feed. The structure itself is non-standard, some browsers don’t support it, so minifiers that adhere to the standards are right to reject that method. Besides, your own point defeats itself: it we write JS for JS interpreters, the implication is to write JS for the broadest compatibility possible. Escaped line feeds reduce that compatibility. And minifiers are increasingly essential tools to reduce bandwidth and execution time, so we SHOULD write JS with minifiers as part of the plan.

    Personally, i find it no easier to read an escaped line feed than “a “+ “b “+ … There’s always something interrupting the end of the line. Sure, concatenating strings suffers a performance hit, but at the point it becomes significant, one should ask why such long strings are being statically coded into Javascript.

  11. Am I missing something? It looks like string literal line continuations _are_ in the spec:

    http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4

    Maybe it’s relatively new but that’s from 2011…?

  12. Ah, I read that more closely and now see that the backslash is only valid if it’s part of something else–not by itself like this post describes. My bad.

  13. This is code will help to generate html code in javascript:….

  14. Michael Haren: The backslash *isn’t* “by itself”; it’s the character right before a newline. However, the spec does specify (ha!) that the newline is *not* a valid character for escape purposes. The only valid escape characters after a backslash are listed explicitly: ‘ ” \ b f n r t v

  15. Jack Sparow

    Excellent, your blog’s always a lifesaver, thanks David!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...