Question:
Why in javascript does \n give me a space and not a new line?
2010-10-25 04:27:10 UTC
every other lang it forces a new line for what comes after and according to what I am reading it says this should too, but when I type for example
document.write('Why is it doing this\n');
document.write('Hello');

It just puts a space between what come next like this:
Why is it doing this Hello

instead of:
Why is it doing this
Hello

I'm not very experienced and I could be missing something obvious, so nice answers would help, thanks.
Three answers:
Emissary
2010-10-25 04:35:04 UTC
If you view the source (depending on your browser) you will probably find that Hello is on a new line, however a new line in the HTML source code doesnt mean anything in most browsers and they wrap the text onto the same line. If you want to force a new line in HTML you need to include the break tag.



document.write('Why is it doing this
\n');
?
2010-10-25 11:38:03 UTC
The text output by "document.write" is not "javacript", but HTML. Hence, your command should be:

document.write("Why is it doing this");



(rb => br, of course, silly editor!)
MILKRONAUT
2010-10-25 11:38:03 UTC
Because, you're outputting HTML. When you output HTML, linebreaks like that won't work, and need to be used. However, if you're sending an alert and need a linebreak, that will work fine. Use \r\n instead, though, that way it'll work in all browsers.



alert('Why is it doing this\r\nHello');


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...