John Doe
John Doe

Reputation: 41

How to make a new line in javascript in a single string

I am trying to make new lines (in this single line of text) as you can see in my index.html file, but it is not working, any help? (\n is where the new line should start,
has not worked either.

index.html:

<html>
        <head>
                <title>test</title>
        </head>
<body bgcolor="black">
<font color="green">
<p id="terminal"></p>
<script>
var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;
function Type() {
        if(count < text.length) {
                document.getElementById("terminal").innerHTML += text.charAt(count);
                count ++;
                setTimeout(Type, speed);
        }
}
Type();
</script>

Upvotes: 1

Views: 87

Answers (2)

Jimenemex
Jimenemex

Reputation: 3166

If you don't want to use <br /> you can easily use the <pre> tag. It's actually easier to use <pre> since you don't have to insert the <br /> at the right location in the DOM.

Taken from the docs.

The HTML pre element represents preformatted text which is to be presented exactly as written in the HTML file.

var text = "this is a test\nthis should be on the next line";
var count = 0;
var speed = 50;

function Type() {
    if(count < text.length) {
        document.getElementById("terminal").innerHTML += text.charAt(count);
        count ++;
        setTimeout(Type, speed);
    }
}
Type();
<html>
  <head>
    <title>test</title>
  </head>
  <body bgcolor="black">
    <font color="green" />
    <pre id="terminal"></pre>
  </body>
</html>

Upvotes: 3

Mwangi Njuguna
Mwangi Njuguna

Reputation: 75

Substitute the new line \n with break <br>

Upvotes: 0

Related Questions