文本中包含转义字符如何保留

328 阅读1分钟

背景:接收到后端返回的文本被包含转义字符,浏览器打印和页面展示均展示错误问题

案例展示:

转义字符如:\n、\r ......

const text = '文本内容聚焦\neewrewr'
<p>展示1:{{ text }}</p>

页面呈现效果:

image.png

解决方法

使用JSON.stringify进行转义保留原有数据,然后把前后符号""去掉,即可

const text = '文本内容聚焦\neewrewr'
let copyText = JSON.stringify(text)
let copyText2 = copyText.substring(1,copyText.length-1)

<p>展示1:{{ text }}</p>
<p>展示2:{{ copyText2 }}</p>

image.png

总结

使用JSON.stringify(text) 以及substring()达到转义字符保留效果

const text = '文本内容聚焦\neewrewr'
let copyText = JSON.stringify(text)
let copyText2 = copyText.substring(1,copyText.length-1)