Why the line break \n does not work in document.write ?

 document.write("lalala \n lalala"); 

    2 answers 2

    Because the browser ignores hyphens, tabs, pl. spaces and other special characters during page rendering.

    Solution 1

     document.write ("lalala <br \/> lalala"); 

    Solution 2

     document.write ("<pre>lalala \n lalala<\/pre>"); 
    • And if in document.write, in addition to the string, there are other data types, such as variable values, just use + "<br />" + or + "<pre>" +, or is there another method for such cases? - Rumata
    • And what do you mean by "other data type". A document is a text - all that is in it is a text, .write writes text. Any javascript values ​​will result in text format when they are output to a document - Mike Nov.
    • That's right, use + "<br \/>" + and "<pre>" ++ "</ \ pre>". For an arbitrary string, you can replace the hyphens \ n by <br> using the replace method. But the best solution, nevertheless, is to surround her <pre>. - Mik

    He works. But the default browser groups all the whitespace characters into one space. It is necessary to slightly change the css to get what you want:

     document.write("lalala \n lalala"); 
     body { white-space: pre-line; }