从数据库(Javascript、HTML、firebase)读取时检测换行符(n)



我正在尝试使用从firebase firestore检索到的字符串,并将其显示在我的HTML页面上。

在store中,我有一个像这样的字符串

第一行 nrow2 nrow3

当我检索它并尝试将其添加到我的页面时,n不注册为换行符。我正在使用预包装和使用测试字符串工作良好。

let text = getString(); //retrieves a string from firebase
document.getElementById('textBox').textContent = text;

显示在我的页面上:

第一行 nrow2 nrow3

以下测试代码:

let text = 'row1nrow2nrow3';
document.getElementById('textBox').textContent = text;

在页面上显示以下内容:

第一行

row2

row3

因此,似乎从数据库中检索到的字符串中的n's与直接在Javascript代码中定义的字符串中放入的n's的读取方式不同。知道为什么吗?我怎么做才能让它读取换行符呢?

类似于@user14063792468在他们的评论中所说的,当存储字符串时,似乎您的换行字符已被转义(即将n转换为\n),因此我会尝试用n(单个反斜杠)替换\n的任何实例,看看是否有效。

下面是替换前后的示例:

let string = 'Newline characters\nare in this\nstring\nfor sure';  // note the double slashes
document.getElementById('before').textContent = string;
let text = string.replace(/\n/g, "n");
document.getElementById('after').textContent = text;
<pre id="before"></pre>
<pre id="after"></pre>

最新更新