1.原生html 下面的写法都不能识别 white-space: pre-line

<h2 style="white-space: pre-line;">test\nhtml</h2>
<h2 style="white-space: pre-line;">'test\nhtml'</h2>
<h2 style="white-space: pre-line;">'test"\n"html'</h2>

解决办法:

(1)正则将\n匹配</br>

<h2 style="white-space: pre-line;">test\nhtml</h2> <script> //使用正则将\n替换成<br/>标签 const h2 = document.querySelector('h2') h2.innerHTML = h2.innerHTML.replace(/\\n/g,'<br>') //注意正则是/\\n/g //也可以分割字符串然后再拼 //h2.innerHTML = h2.innerHTML.split('\\n').join("<br>")//注意\\n </script> </body>

(2) 获取到标签,用html赋值

<h2 style="white-space: pre-line;">test\nhtml</h2> <script> const h2 = document.querySelector('h2') h2.innerHTML = 'test\nhtml' </script> </body>

2.vue vue中在scrpit中定义变量str,在html中用{{str}}渲染就行

<template>
  <div class="test">
    <h2 style="white-space: pre-line">{{ str }}</h2>
  </div>
</template>
<script setup lang="ts">
let str = 'test\nvue'
</script>

3.react

const str = 'test\nreact'
return <h1 style={{ whiteSpace: 'pre-line' }}>{str}</h1>

总结:html没法识别\n,可以转换成<br>标签,或者在js里操作。