HTML无法按预期呈现JavaScript换行符

时间:2019-04-10 07:48:16

标签: javascript html

我有一个包含一些文本的json文件,其中一些文本可能包含一些换行符

"surchargeNoteText":"Please note \r \n that pre-payments will take up to 2 business \r \n days to be allocated to your reservation",

我尝试使用\ r和/或\ n,结果是这样 enter image description here

所以,有趣的是,当检查html时,输出是正确的,带有2条换行符。

enter image description here

那么,这里有什么提示吗?

5 个答案:

答案 0 :(得分:1)

CSS 以下添加将解决您的问题。谢谢

p.jss98 {
   white-space: pre-wrap;
}

答案 1 :(得分:1)

使用<pre>标签将文本设置为所需的格式

<pre>
I am inside
   a pre
          Tag!
<pre>

答案 2 :(得分:0)

HTML呈现时,它将忽略空格。因此,唯一的方法是使用换行符。

使用<br/>代替\n,它将正常工作

document.write()函数将HTML写入元素。

let obj= {"surchargeNoteText":"Please note \r \n that pre-payments will take up to 2 business \r \n days to be allocated to your reservation"};

console.log(obj.surchargeNoteText);

let htmlstring = obj.surchargeNoteText.replace(/(\r\n|\n|\r)/gm, "<br>");

console.log(htmlstring);

document.getElementById('text').innerHTML =htmlstring;
<div id="text"></div>

答案 3 :(得分:0)

在HTML中,您需要添加<br />来换行。

"surchargeNoteText":"Please note <br /> that pre-payments will take up to 2 business <br /> days to be allocated to your reservation",

答案 4 :(得分:0)

使用&nbsp;代替\r,并使用<br/>代替\n。在HTML中,\r\n不起作用。