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