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");
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.
\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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With