CuriousWebDeveloper
CuriousWebDeveloper

Reputation: 173

Do text editor line breaks end string contents in javascript?

In the following script [piece of a script],

document.write(
    '<div class="user-info-wrap">
    <div class="user-info-left">'

my text editor stops coloring the third line as if it is not included in the single quotes. Do text editor line breaks end (javascript string) quote contents?

If so, it would mean that I need to do the following, it seems to me, which seems to not make sense, so possibly the text editor's coloring schematics are in error.

 document.write(
     '<div class="user-info-wrap">' +
     '<div class="user-info-left">'

Which is it?

Upvotes: 3

Views: 2654

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

Update

With ECMAScript version 6 (ES6) now standard in all major browsers, you no longer need to do the escape trick anymore. That was simply a "trick" for ES5. Moving forward, all you need to to is wrap you string within two back-ticks `.

var multiStr = `This is the first line
This is the second line
This is more...`;

Original response circa 2014

You can do either of the two:

Concatenation:

var multiStr = "This is the first line " +
"This is the second line " +
"This is more...";

Escaping:

var multiStr = "This is the first line \
This is the second line \
This is more...";

Both output:

This is the first line This is the second line This is more...


Note: With the escaping method, leading white-space on sequential lines are not ignored.

var multiStr = "This is the first line \
    This is the second line \
    This is more...";

This will output:

This is the first line     This is the second line     This is more...


To answer your question:

Not all text-editors support JavaScript mult-line strings highlighting. Notepad++ handles it quite well, whereas VI/VIM do not display the whole string in red. VI/VIM only knows how to highlight a string on the same line where the opening-quote is placed. If you notice, VI/VIM thinks that you created a new String (on the last line) with the first character being the semi-colon. This is not true, this is just a flaw in the editor's highlighting.

enter image description here

Upvotes: 7

elixenide
elixenide

Reputation: 44823

Javascript does not allow for multi-line strings without escaping. So, this doesn't work:

var foo = "bar
bar";

You can put the entire string on one line, like:

var foo = "bar\nbar"; // includes the line break

Or you can escape the line break with \, like this:

var foo = "bar\
bar";

In the latter example, foo is barbar (no line break). You can add spaces or line breaks manually, like this:

var foo = "bar \
bar";

var foo = "bar\n\
bar";

Note that any leading white space on the lines after \ is not ignored, so this:

var foo = "bar\
    bar";

Gives foo the value

bar     bar

And, of course, you can always just concatenate parts of the string, like this:

var foo = "bar"
+"bar";

Upvotes: 0

Related Questions