35

我正在使用这个插件来解析 bbcode bbcodeparser

但它没有转换\n<br/>.

我试着添加这个:

replace(/\r?\n|\r/g, '<br>')

......但它没有工作。

如何实现换行功能?

4

4 回答 4

124

If you are doing this to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.

<span style="white-space: pre-line">@Model.CommentText</span>
于 2014-05-19T11:27:02.293 回答
14

上面的答案帮助我解决了我的问题,但我进一步挖掘并发现了一些关于white-space属性的额外信息。我希望它可以帮助像我这样的人:

什么是white-space财产:

white-space 是一个 CSS 属性,有助于控制元素文本中的空白和换行符的处理方式。它可以采用以下值:normal、nowrap、pre、pre-line、pre-wrap。

在此处输入图像描述

于 2019-07-24T20:44:28.300 回答
2

\r\n实际上,在使用 PHP nl2br时,浏览器不会将其视为真正的换行符,而在 Javascript 中,您可以使用下面的函数进行nl2br()等效。

function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');}
于 2014-01-10T08:56:00.463 回答
2

这对我有用

const regex = /\\n|\\r\\n|\\n\\r|\\r/g;
string.replace(regex, '<br>');
于 2020-07-14T11:28:22.780 回答