How do I break a string across more than one line of code in JavaScript?

How do I break a string across more than one line of code in JavaScript?

Is there a character in JavaScript to break up a line of code so that it is read as continuous despite being on a new line?
Something like….

1. alert ( “Please Select file
2. \ to delete” );

Solutions/Answers:

Solution 1:

In your example, you can break the string into two pieces:

alert ( "Please Select file"
 + " to delete");

Or, when it’s a string, as in your case, you can use a backslash as @Gumbo suggested:

alert ( "Please Select file\
 to delete");

Note that this backslash approach is not necessarily preferred, and possibly not universally supported (I had trouble finding hard data on this). It is not in the ECMA 5.1 spec.

When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:

if(SuperLongConditionWhyIsThisSoLong
  && SuperLongConditionOnAnotherLine
  && SuperLongConditionOnThirdLineSheesh)
{
    // launch_missiles();
}

Solution 2:

Put the backslash at the end of the line:

alert("Please Select file\
 to delete");

Edit    I have to note that this is not part of ECMAScript strings as line terminating characters are not allowed at all:

A ‘LineTerminator‘ character cannot appear in a string literal, even if preceded by a backslash \. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as \n or \u000A.

So using string concatenation is the better choice.

Related:  How do I get data from a data table in javascript?

Update 2015-01-05    String literals in ECMAScript5 allow the mentioned syntax:

A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A.

Solution 3:

ECMAScript 6 introduces template strings:

Template strings are string literals allowing embedded expressions.
You can use multi-line strings and string interpolation features with
them.

For example,

alert(`Please Select file   
to delete`);

will alert

Please Select file   
to delete

Solution 4:

Break up the string into two pieces 

alert ("Please select file " +
       "to delete");

Solution 5:

Interesting to note. Tried:

alert("Some \
    string \
    wrapped \
    across \
    mutliples lines.")

And this worked. However, on accident!, there was a space character following the final backslash (all other backslashes were at the end of the line). And this caused an error in the javascript! Removing this space fixed the error, though.

Related:  Setting the HTML

This is in ADT for Android using Cordova.

Solution 6:

You can just use

1:  alert("Please select file" +
2:        " to delete");

That should work