Cristien
Cristien

Reputation: 23

Why does my template literal not create a new line?

var request = require("request");
request("https://jsonplaceholder.typicode.com/users/1", function(
  error,
  response,
  body
) {
  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB. 
     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }
});

Can someone explain why there is not a new line in my template literal here?

Upvotes: 1

Views: 967

Answers (1)

Barmar
Barmar

Reputation: 781149

The template literal does contain a newline. But when the browser renders the HTML, it re-wraps the line.

If you want to see the text without being reformatted, put it in a <pre> element or set the style of the element to white-space: pre; with CSS.

Or use <br> in the HTML:

  if (!error && response.statusCode == 200) {
    //Things worked!
    var parsedData = JSON.parse(body);
    console.log(parsedData);
    document.getElementById(
      "text"
    ).innerHTML = `${parsedData.name} lives in Saint John NB.<br>
     Her street name is ${parsedData.address.street}`; //This should be a new line??????
  }

Or assign to .innerText instead of .innerHTML, this retains newlines (but not other formatting like indentation).

Upvotes: 3

Related Questions