The @Sergio suggestion is perfect, I’m writing this answer just to clarify the behavior of HTML in relation to spaces...
What happens is that, in the case of your example, HTML is ignoring breaks and leaving them as spaces. This happens because of the property white-space
of css
.
See more here: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
How are you wearing a document.write
, should be writing to the body
, which by default has this property as "normal", which causes it to behave like this, as documented in the link above:
"Blanks strings are collected. New characters
line in the code are treated as other blank spaces. Lines
break as needed to fill the lines of the boxes
(boxes)."
That is, breaks are treated as spaces. Now, if you use an element that has another behavior of white-space
, or change property white-space
in the body
, it can change how line breaks appear, see this:
document.write("<pre>");
document.write("Linha1\nLinha2\nLinha3");
document.write("</pre>");
For the example above, I used the element <pre>
, which by default has the property white-space
as pre
. The drawback is that the element has other styles.
See now if you change the behavior of body
(just for study to see how it works), and break, I will use the method writeln
that already adds a line break without needing the \n
:
document.writeln("---- isso é um teste ----");
document.writeln("Linha1");
document.writeln("Linha2");
document.writeln("Linha3");
body {
white-space: pre;
}
So the behavior can be controlled with css
, avoiding <br>
, but it depends on the context and how the page is. Anyway, still avoid using document.write
, it is preferable to create an element and add the content directly to it (div, for example), this helps to better control the HTML, and can use other formatting.
Have you tested with
<br>
instead of\n
?– Sergio
\n
break line only in HTML (Inspecione the element and see the result). As Sergio said, try the tag<br>
– Rafael Tavares