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

问题描述

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

@H_404_5@
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,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>')

,

您需要使用divwhite-space: pre-wrap设置样式:

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

let str = `

          Woke up this morning,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>