Search code examples
javascripthtmlline-breakstemplate-literalsend-of-line

Preserve line breaks when adding template literal to html with JavaScript


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>


Solution

  • 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>