Preserve line breaks when adding template literal to html with JavaScript

1.1k views Asked by At

How would I preserve the end-of-line characters in the str template literal below when adding to html?

let str = `

          Woke up this morning,
           
           ate a baguette,
           
           smiled at a person and they smiled back.`

document.getElementById("example").innerHTML = `<div>Dreamfit:</div><div>${str}<div>`
<div id="example"></div>

3

There are 3 answers

2
Joan Albert On BEST ANSWER

You need to style your div with white-space: pre-wrap:

So your code should look like:

let str = `

          Woke up this morning, 
ate a baguette,
           
           smiled at a person and they smiled back.`

document.getElementById("example").innerHTML = `<div>Dreamfit:</div><div style="white-space: pre-wrap;">${str}<div>`
<div id="example"></div>

2
Ozone On

You can do this with the <pre> tag:

let str = `<pre>

          Woke up this morning,
           
           ate a baguette,
           
           smiled at a person and they smiled back.</pre>`

document.getElementById("example").innerHTML = `<div>Dreamfit:</div><div>${str}<div>`
<div id="example"></div>

0
norbitrial On

You can use .replace() also as:

let str = `

          Woke up this morning,
           
           ate a baguette,
           
           smiled at a person and they smiled back.`

let html = `<div>Dreamfit:</div><div>${str.replace(/\n/g, '<br>')}<div>`

document.getElementById("example").innerHTML = html
<div id="example"></div>

See the essential part separately here: str.replace(/\n/g, '<br>').