从数据库(JavaScript,html,firebase)读取时检测线路断裂(\ n)

发布于 2025-02-04 11:02:20 字数 673 浏览 3 评论 0原文

我正在尝试使用从Firebase Firestore检索到的字符串,并在我的HTML页面上显示它。

在商店中,我有一个字符串,看起来像该

行1 \ nrow2 \ nrow3

当我检索它并尝试将其添加到我的页面中。我使用的是预装,并且使用测试弦乐效果很好。

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

在我的页面上显示此内容:

row1 \ nrow2 \ nrow3

以下测试代码:

let text = 'row1\nrow2\nrow3';
document.getElementById('textBox').textContent = text;

在页面上显示以下内容:

row1

Row2

Row3

因此,从数据库中检索到的字符串中的\ n似乎与直接在JavaScript代码中定义的字符串中的\ n读取的方式相同。知道为什么吗?我该怎么做才能让它阅读界限?

I'm trying to use a string retrieved from firebase firestore and display it on my HTML page with line breaks.

In the store, I have a string that looks like this

row1\nrow2\nrow3

When I retrieve it and try to add it to my page the \n's do not register as line breaks. I am using pre-wrap and using a test-string works fine.

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

Shows this on my page:

row1\nrow2\nrow3

The following test code:

let text = 'row1\nrow2\nrow3';
document.getElementById('textBox').textContent = text;

Shows the following on the page:

row1

row2

row3

So it seems like the \n's in the string retrieved from the database are not read the same way as the \n's that are put inside the string defined directly in the Javascript code. Any idea why? And what can I do to make it read the line breaks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜扑 2025-02-11 11:02:20

类似于 @user14063792468在评论中所说的话,看来您的newline字符已被逃脱(即,converts \ n to \ code> \\ n),因此我将尝试用\\ n将任何实例替换为\ n(单个Backslash),然后查看是否有效。

这是一个替代之前和之后的外观的示例:

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>

Similar to what @user14063792468 said in their comment, it appears your newline characters have been escaped (i.e., converts \n to \\n) when a string is stored, so I'd try to replace any instances of \\n with \n (single backslash) and see if that works.

Here's an example of how this might look before and after the replacement:

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文