Spanning javascript strings across multiple lines

I came across a weird feature of javascript last week, a way of spanning javascript strings over multiple lines.

To do it you put a ‘\’ character just before the line break and javascript knows it should keep going on the next line:

  1. var mystring = "hello \
  2.                world";

I found it because I was trying to test something with a string that was coming over ajax split across multiple lines and I wanted to test a static string with the same space and tab characters in it.

I think this is quite handy if you want to create a big long bit of HTML. I find it a bit more readable than having lots of plus signs all through the code:

  1. myElement.innerHTML = " \
  2.        <ul> \
  3.            <li>First item</li> \
  4.            <li>Second item</li> \
  5.            <li>Third item</li> \
  6.        </ul>";

The javascript line continuation character doesn’t put a line break in the string. You still need to explicitly put in a \n character if you want a line break in the string.

Not part of official javascript standard

It’s not part of the EMCAScript standard. It’s something the browsers support for backwards compatibility. I guess that means it’s possible it could one day be deprecated. That’s a bit of a pity because I think it’s quite useful for making string concat easier to read.

Posted on 13 May 07 by Helen Emerson (last updated on 13 May 07).
Filed under Javascript

Comments

Armando Wall 26 Jun 2007

Javascript, as many other languages such as Java, C#, PHP, Actionscript, C++, Objective-C, etc, borrowed much of its syntax from the C language (if you don’t believe me, just google for source code or a tutorial on C). Having said that, this is a feature originally found in C, so it’s safe to assume that Javascript inherited it from it as well.

- Armando (“Rafael”) Wall.

Myself 16 Jun 2008

It’s a different solution:

Using a line break with the escape character, you just create a string literal, though it’s defined in two lines of code.

Using + you are creating two string objects and concatenating them to create a third string object. That takes more time and memory. It may seem it’s not so bad, but if you do that many times with a not too powerful architecture (i.e. java ME), you will end up slowing your application because memory allocation and garbage collection will be quite more requent.

GodsBest 30 Dec 2011

Just what I needed; thank you so much! I just don’t know what I would have done without this post.

We have a JSP file fetching an rss feed and creates a JSON object. One data element had a value spanning several lines in the feed for the first time (test case did not include this). In trying to manipulate the JSON we were getting “unterminated string literal”. After replacing every line break with “\” everything works great!!

I owe you big time Helen :)