Sharthrak Niroshan
Sharthrak Niroshan

Reputation: 61

newline doesn't work in javascript

When I use the new line character in java-script it is not working. I post my code below.

var i=1;
while(i<=5)
{
    document.write(i+"\n");     
    i++;
}

The outcome looks like this. 1 2 3 4 5

Upvotes: 1

Views: 2685

Answers (3)

adam-beck
adam-beck

Reputation: 6009

The reason that you are not seeing the newline characters as you expected is because you are likely trying to render this in HTML. If that is the case, "\n" is not rendered as a newline. Which is why @Yuriy Galanter said to include <br/> which is. If you were to write to the console.log then it would work as you have it written.

Upvotes: 1

EduardoFernandes
EduardoFernandes

Reputation: 3439

Instead of "\n", use "<br/>", as the code below:

var i=1;
while(i<=5)
{
    document.write(i+"<br/>");     
    i++;
}

Here is the JSFiddle. When accessing it, click run to see the code.

Upvotes: 1

doniyor
doniyor

Reputation: 37846

since you are writing into HTML Document, you should write <br>

var i=1;
while(i<=5){
 document.write(i+"<br/>");     
 i++;
}

Upvotes: 3

Related Questions