Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
CuriousWebDeveloper Avatar asked Jan 29 '26 11:01

CuriousWebDeveloper


1 Answers

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

like image 140
Mr. Polywhirl Avatar answered Jan 30 '26 23:01

Mr. Polywhirl