Javascript line breaking is not working

Asked

Viewed 123 times

1

I’m trying to insert a line break into a simple code:

 var meuNome = "Danilo Costa";
var idade = 18;
var ocupacao = "dev Front End";
var interesses = [
    ['Jogos',['world of warcraft']],
    ['musica',['SuperCombo']],
    ['livros',['O nome da rosa - Umberto Eco']]];

document.write('Olá, eu me chamo '+ meuNome +', tenho '+idade +' anos, e sou um ' + ocupacao + ' \nmeus interesses são:'+interesses[0]);

When I run this code, the line break in the part " nmeusinteresses" does not work... Why does this happen? inserir a descrição da imagem aqui

  • 3

    Have you tested with <br> instead of \n?

  • \n break line only in HTML (Inspecione the element and see the result). As Sergio said, try the tag <br>

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.