How do I break a string across more than one line

2019-01-01 07:19发布

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" );

8条回答
只靠听说
2楼-- · 2019-01-01 07:45

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
查看更多
若你有天会懂
3楼-- · 2019-01-01 07:47

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();
}
查看更多
登录 后发表回答