显示新行<br>在数据库中时 在浏览器中

Showing new lines <br> in the browser when having in the database

本文关键字:数据库 浏览器 br 新行 lt 显示 gt      更新时间:2023-09-26

在mongo中,我有一个带有类似reviewText: 'this is line 1'nthis is line 2',的字段的文档。我是从textarea得到的,所以'n在那里,因为用户点击了回车键。我想在带有换行符的div中打印屏幕上的文本(如果他点击多个输入,最好只有一个换行符)。我不知道如何做到这一点。我不会在屏幕上显示任何'n

我在EJS中做<div class = "displayReview"><%= e.reviewText %></div>,它只是在一行上打印所有内容。它让我在浏览器中获得<div class="displayReview">this is line 1 this is line 2</div>

我的路线中有一个更新文档的地方,比如:

    .then(function(returnedReviews){
        console.log(" returnedReview ",returnedReviews);
        returnedReviews.forEach(function(e){
            e.momented = moment(e.createdAt.getTime()).fromNow()
            // e.reviewText = e.reviewText.replace(/'r?'n/g, '<br />')
        })

我试着做我在评论中所做的。但这显然只是将<br />(文本)放在字符串中,而不是HTML中。我希望有一个简单的方法来做这件事。

当它被打印到用户在发送表单之前点击textarea中的回车键的屏幕上时,我希望看到换行。如果用户连续多次点击回车键,应该只有一个换行。

首先,标准化换行符并将其减少为一个(符合您的要求):

e.reviewText = e.reviewText.replace(/'r?'n/g, ''n');
e.reviewText = e.reviewText.replace(/'n+/g, ''n');

这会将数据放入标准表单中。以特定方式显示数据是模板的工作。我还没有使用过EJS,但从他们的示例代码来看,沿着以下几条线应该可以工作:

<div class = "displayReview">
  <% e.reviewText.split(''n').forEach(function(ln) {%>
     <%= ln %><br>
  <% } %>
</div>

在这种特殊的情况下,也许在模板呈现数据后,数据本身就会被丢弃,因此将数据操作与表示分离是一种形式,但这仍然是一个好习惯,并使代码稍后更容易修改。

还值得一提的是,如果您能够修改.displayReview.的CSS,则不需要严格使用JavaScript来实现这一点(除非用户连续多次点击回车按钮,否则会有多个换行符)

这可以通过将空白属性更改为预、预行或预换行来实现。

示例:

.displayReview {
  white-space: pre-wrap;
}

从MDN来看,预包装、预包装和预包装之间的区别是

pre

Sequences of whitespace are preserved, lines are only broken at newline characters in the source and at <br> elements.

预包装

Sequences of whitespace are preserved. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.

预连线

Sequences of whitespace are collapsed. Lines are broken at newline characters, at <br>, and as necessary to fill line boxes.