Reputation: 15652
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");
Upvotes: 3
Views: 425
Reputation: 32052
\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');
Upvotes: 2
Reputation: 837926
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.
Upvotes: 7
Reputation: 20235
\n
is a way of writing a new line (line break). So, "Hello World!\nHow are you?"
would output like this:
// Hello World!
// How are you?
instead of this:
// Hello World!How are you?
You can use the "\" before other letters too... like \t
which is a tab. or \\
which makes a back-slash. But just entering \
in a string will output nothing.
Upvotes: 1