Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, what is the difference between '\' and '\n'?

I figure that both \ and \n can be used as a line break. What is the difference?

EDIT: Sorry I realized that I was wrong. The tutorial was talking about / as a line break for the programmer, which wasn't displayed, i.e:

alert("Hi \
there");
like image 905
DarkLightA Avatar asked Sep 01 '26 15:09

DarkLightA


2 Answers

A slash at the end of a line inside a string allows you to write the rest of the string on the following line. The resulting string won't actually contain a line break at that point. It is purely used to help make the source code more readable.

var foo = "This string \
has only \
one line.";

// Result:
// This string has only one line.

A "\n" actually inserts a linebreak.

var bar = "This string has\ntwo lines.";

// Result:
// This string has
// two lines.
like image 102
Mark Byers Avatar answered Sep 03 '26 04:09

Mark Byers


\n is the only correct escape code for a newline (short of using things like \u000a or similar).

Note that the below code does not actually insert line breaks (would still need the actual \n escape code):

var foo = 'qwertyuiopasdfghjkl\
qwertyuiopasdfghjkl\
qwertyuiopasdfghjkl';

The result is 'qwertyuiopasdfghjklqwertyuiopasdfghjklqwertyuiopasdfghjkl'. I also don't recommend the above code because indenting the continuation lines causes problems with unwanted spaces in your string. One good alternative, though, is:

var foo = [
    'qwertyuiopasdfghjkl',
    'qwertyuiopasdfghjkl',
    'qwertyuiopasdfghjkl'
].join('\n');
like image 23
PleaseStand Avatar answered Sep 03 '26 05:09

PleaseStand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!