254

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" );
Alex Angas
  • 59,219
  • 41
  • 137
  • 210
T.T.T.
  • 33,367
  • 47
  • 130
  • 168

11 Answers11

331

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();
}
Michael Haren
  • 105,752
  • 40
  • 168
  • 205
  • Can you break up an if statement ? – T.T.T. Feb 03 '09 at 18:29
  • 17
    But beware of the automatic semicolon insertion mechanism: Try to have return on one row and a "string" on the next one at the end of the function and you get undefined as a result. – some Feb 03 '09 at 21:30
  • Is this standards-compliant? Will all compliant browsers support it? Do *older* browsers support it today? None of these important questions covered, -1. – ulidtko Sep 24 '13 at 13:33
  • 4
    Well...if you're going to ask a bunch of new questions not already asked, you've got to give us a chance to answer them. I updated my answer with an unsatisfying conjecture. – Michael Haren Sep 24 '13 at 14:55
  • 2
    Beware of backslash. It will eat all blancks until it find a no-blank. So the example will "alert": Please Select fileto delete. If you want the white space between file and to, you should put it before de backslash. – jgomo3 Aug 12 '15 at 00:13
  • make that one big line. – Ajay Takur Apr 27 '16 at 11:52
  • Re: line continuation backslash eating whitespace on the next line - don't rely on this (f.ex. while formatting your code). I suspect this is dependent on the JS implementation. Node does not eat extra whitespace as I write this, so it will end up as part of your string. – kvsm Oct 23 '16 at 18:11
  • 1
    `SuperLongConditionWhyIsThisSoLong` Because this will launch a missile and you wants to be extra safe –  Nov 22 '16 at 12:23
  • I agree with the concatenation operator usage. – Saryk Jul 26 '17 at 15:09
  • The backslash operator leads to issues in real code, since it will add spaces if included in an indented block (e.g. a function), which is very common. See my answer below. – belvederef Oct 05 '20 at 10:10
48

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.


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.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 1
    [ECMAScript5](http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4) allows it: "*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`.*" – Oriol Jan 05 '16 at 15:22
  • 1
    @Oriol Thanks for the note, updated the answer accordingly! – Gumbo Jan 05 '16 at 19:45
  • 1
    Is this problematic if the file was created in Windows. In other words lines terminated with `\r\n` instead of `\n`? – Adam Plocher Aug 07 '17 at 11:52
  • @AdamPlocher: No; "" is considered a single line terminator character. See https://262.ecma-international.org/5.1/#sec-7.3. – Gerhard Aug 16 '22 at 21:06
38

ECMAScript 6 introduced 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
Andreas
  • 5,393
  • 9
  • 44
  • 53
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    Wow awesome. To get these ` ` on the keyboard press SHIFT + ´ two times. On a german keyboard that key is near the backspace key. – Nadu Aug 09 '16 at 13:51
  • 1
    @Nadu That depends on a keyboard. Mine has a `\`` key. Since it's a modifier it's not written directly. That's probably why you thought you should press it twice, but that will write two of them. Press spacebar to write only one. – Oriol Aug 09 '16 at 15:23
  • 1
    Unbelievable that it took so long to allow multiline strings without fancy hacks... Question is: What will be used as line separators - a hardcoded char(s) or the line break char(s) of the document? – StanE May 18 '17 at 23:15
  • 1
    There is problem with ` ` in case when you want to do magnification of *.js file. – Raskolnikov Jun 12 '17 at 13:19
  • 1
    Consider, that still in march 2018 only 89% of global used browsers support template strings according to caniuse.com https://caniuse.com/#feat=template-literals – FFirmenich Mar 27 '18 at 06:44
  • Unfortunately it is not supported by IE11 so i wouldn't recommend it. – Corentin Jan 03 '19 at 16:59
  • 1
    Since indentation isn't stripped, I find this feature rather useless in a real codebase. – Michael Gummelt Oct 19 '19 at 18:06
  • @FFirmenich August 2020 and we're at 95.44%. It's just IE (as usual). – Andreas Aug 12 '20 at 06:26
  • @MichaelGummelt They're called string literals for a reason. Everything inside the backticks is taken literally. – Clonkex Jul 20 '22 at 03:18
9

Break up the string into two pieces 

alert ("Please select file " +
       "to delete");
Simon D
  • 4,150
  • 5
  • 39
  • 47
Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122
6

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.

This is in ADT for Android using Cordova.

There
  • 498
  • 6
  • 18
  • 1
    Spent most of my day fighting this issue and I also discovered, thanks to you, that a space character after any of the slashes was causing my ionic app to not compile. Thank you! – rekordboy Feb 24 '16 at 06:08
  • 3
    Can't believe anyone commented that this will include whatever indentation was in the code as part of the string, so that the example becomes `Some\n<4 spaces>string\n<4 spaces>wrapped\n<4 spaces>across\n<4 spaces>multiple lines.` – JHH May 24 '19 at 09:03
1

You can just use

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

That should work

Jaime Garcia
  • 6,744
  • 7
  • 49
  • 61
1

You can break a long string constant into logical chunks and assign them into an array. Then do a join with an empty string as a delimiter.

var stringArray = [
  '1. This is first part....',
  '2. This is second part.....',
  '3. Finishing here.'
];

var bigLongString = stringArray.join('');
console.log(bigLongString);

Output will be:

  1. This is first part....2. This is second part.....3. Finishing here.

There's a slight performance hit this way but you gain in code readability and maintainability.

blackcatweb
  • 1,003
  • 1
  • 10
  • 11
1

The backslash operator is not reliable. Try pasting this function in your browser console:

function printString (){
  const s = "someLongLineOfText\
  ThatShouldNotBeBroken";
  console.log(s);
}

and then run it. Because of the conventional (and correct) indentation within the function, two extra spaces will be included, resulting in someLongLineOfText ThatShouldNotBeBroken.

Even using backticks will not help in this case. Always use the concatenation "+" operator to prevent this type of issue.

belvederef
  • 2,195
  • 19
  • 16
-1

A good solution here for VSCode users, if a string breaking down into multiple lines causes the problem (I faced this when I had to test a long JWT token, and somehow using template literals didn't do the trick.)

Sujit Y. Kulkarni
  • 1,186
  • 3
  • 22
  • 37
-4

I tried a number of the above suggestions but got an ILLEGAL character warning in Chrome code inspector. The following worked for me (only tested in Chrome though!)

alert('stuff on line 1\\nstuff on line 2);

comes out like...

stuff on line 1
stuff on line 2

NOTE the double backslash!!...this seems to be important!

-6

No need of any manual break in code. Just add \n where you want to break.

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

This will show the alert like

Please select file 
to delete.
Narendra
  • 3,069
  • 7
  • 30
  • 51
  • down voter, can u please tell the reason for downvote. This solutions works for me always. – Narendra Jun 03 '13 at 10:58
  • 32
    I don't know who down voted or why; but just a guess: the op wanted to know how to extend a text literal across multiple lines of code, rather than how to insert a line break in the output. – Zarepheth Aug 27 '13 at 19:57
  • That's just not what the OP was asking for. He wanted to know how to break long strings in his code, not in the UI. – Andreas Aug 12 '20 at 06:22