0

specs

I am working on Linux Mint 14. I started on JavaScript recently and I tried to do some output formatting(printing random numbers, one per line) and as usual used \n. But this does not seem to work.

On both the chromium web browser and mozilla firefox, only a space shows up.

code

<HTML>

<HEAD>

<TITLE> GENERATE RANDOM NUMBERS AND PRINT THEM </TITLE>

<BODY>

<div id='container'>

<button onclick='startPrinting()'>Generate random numbers </button>

</div>

</BODY>

</HTML>

</HEAD>

<script>

function startPrinting()
{

var b = document.getElementById('container');

//b.innerHTML += Math.floor(Math.random() * 1000);

b.innerHTML += '<br>The following are some random numbers.<br>';

for(var i =1;i<10;i++)
{

b.innerHTML += '\n';

b.innerHTML += i + '.' + Math.floor(Math.random() * 1000);

}

}

</script>

I tried <br> and this worked well. But now I have many files where I have \n.

So is there a way that I can tell the script to replace all occurences of \n with <br>?

If possible please give an answer that will ensure that i have to add only a few lines of code to my existing files.

(I am looking for something like #define in C++)

please help me resolve this issue.

Frederick Roth
  • 2,748
  • 4
  • 28
  • 42
IcyFlame
  • 5,059
  • 21
  • 50
  • 74
  • 1
    Your issue is not that `'\n'` isn't a newline, it's that when *rendering HTML* all whitespace is treated the same (as spaces). – jamesdlin May 29 '13 at 10:35

2 Answers2

0

You can do it inside a pre tag, which expects pre-formatted text and will treat \n as a newline:

<pre id="container">
    1
    2
    3
<pre>

Will ouput:

1
2
3

You can try this out here on JsFiddle

Henridv
  • 766
  • 12
  • 23
0

IF I have understood the question correctly, you need a list of numbers, vertically ?

If so then Its as simple as below.

function startPrinting()
    {

    var b = document.getElementById('container');

    var nums =[1,2,3,4,5,6,7,8,9,10] 

    var html =[]
    html.push("<ul>")
    for(var i =1;i<nums .length;i++)
    {

    html.push("<li>"+nums[i] +"</li>"); 

    }
    html.push("</ul>")
    b.innerHTML =html.join("");
    }
varun
  • 4,522
  • 33
  • 28