-2

I am having trouble creating a new line in JavaScript. When I use document.write() and enter \n at the start, it doesn't create a new line. How do I create new lines? (By the way, I am just a beginner)

Code:

var myString;    
myString = 42;    
document.write("myString is currently: " + myString);    
myString = myString + 1;    
document.write("\n myString is currently: " + myString);    
  • You're writing HTML, which means you need `
    `. If you want `\n` to create a new line, you need to wrap the text in `
    ` and `
    `
    –  Sep 05 '17 at 10:15
  • It's better to learn not to use `document.write` even in exercises; it should be used only in very few special cases. – JJJ Sep 05 '17 at 10:18
  • 3
    Possible duplicate of [How do I create a new line in Javascript?](https://stackoverflow.com/questions/5758161/how-do-i-create-a-new-line-in-javascript) – JJJ Sep 05 '17 at 10:26

1 Answers1

0

You are using document.write that will render the text inside it as an HTML thus, the \n is not detected as a new line character but simply as a escape character. That is why you will get the output without n as n is escaped by backslash \. So, in your case you need to use the HTML line break <br/>.

var myString;    
myString = 42;    
document.write("myString is currently: " + myString);    
myString = myString + 1;    
document.write("<br/> myString is currently: " + myString);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62