apc518
apc518

Reputation: 303

Why does \n sometimes act as a space in javascript instead of a new line character?

The code below produces "hello world" on one line, rather than printing each word on a separate line. Why?

This happens whether I use '\n' or "\n"

If I put <br/> in place of \n that works, but I want to make the javascript string itself have a line break, not the HTML.

I am very confused. It seems like I'm basically copy-pasting from other people's code which has worked, yet this doesn't? I'm running it in Tryit Editor v3.6

<p id="foo"></p>
<script type="text/javascript">
    var testString = "hello" + "\n" + "world";
    document.getElementById("foo").innerHTML = testString;
</script>

Upvotes: 4

Views: 4319

Answers (3)

Felipe Jacob
Felipe Jacob

Reputation: 394

In HTML the new line is <br> and not \n.

<p id="foo"></p>
<script type="text/javascript">
    var testString = "hello" + "<br>" + "world";
    document.getElementById("foo").innerHTML = testString;
</script>

UPDATE:

If you want to keep the break-line in both (javascript and HTML), try this:

<p id="foo"></p>
<script type="text/javascript">
    var testString = "hello" + "\n" + "world";
    console.log(testString); //Here you can see the break line
    document.getElementById("foo").innerHTML = testString.replace(/\n/g, '<br>'); //At the browser you will see the break line too
</script>

Upvotes: 3

Quentin
Quentin

Reputation: 943108

The JavaScript is irrelevant. Any group of whitespace in HTML, except under certain circumstances (such as being in a <pre> element) is treated as a single space.

<p>Hello,
      World</p>

If you want a new line then use a <pre> element, apply the white-space CSS property, or add a <br> element (etc. etc.) as is appropriate for the semantics of the data you are adding to do the document.

Upvotes: 3

caravana_942
caravana_942

Reputation: 671

That's because you are surrounding that string in a paragraph tag. If you use the console.log() method you should see that \n is a new line character.

If you want to break the line, use the <br/> tag

Upvotes: 1

Related Questions