Posted: 3 years ago

Filed under: Javascript

Tagged with: Javascript

Follow comments

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.

Comments

  1. Armando Wall Says:

    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.

  2. Myself Says:

    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.

Leave a Reply