使用 JavaScript 将模板文字添加到 html 时保留换行符

Preserve line breaks when adding template literal to html with JavaScript

添加到 html 时如何保留下面 str 模板文字中的行尾字符?

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>

您可以使用 <pre> 标签执行此操作:

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>

您可以将 .replace() 用作:

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>

这里单独查看重要部分:str.replace(/\n/g, '<br>')

您需要使用 white-space: pre-wrap 设置 div 的样式:

因此您的代码应如下所示:

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>