Javascript 如何将 \n 转换为 HTML 换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14948223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert \n to HTML line break
提问by user007
I am using this plugin to parse bbcode bbcodeparser
我正在使用这个插件来解析 bbcode bbcodeparser
but it has no functionality to convert \nto <br/>.
但它没有转换\n为<br/>.
I tried adding this:
我尝试添加这个:
replace(/\r?\n|\r/g, '<br>')
...but it didn't work.
......但它没有用。
How can I implement line break functionality?
如何实现换行功能?
回答by Foreever
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-spaceattribute pre-linevalue.
如果您这样做是为了在 html 中显示新行并返回回车,那么您不需要明确地这样做。您可以通过设置white-space属性行前值在 css 中完成。
<span style="white-space: pre-line">@Model.CommentText</span>
回答by Vijay Lathiya
actually, Browsers doesn't treat \r\nas real new-lines, in PHP nl2brused, where as in Javascript you can use below function for nl2br()equivalent.
实际上,浏览器并不将\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, '' + breakTag + '');}
回答by Rajat Badjatya
The above answer helped me to fix my problem but I dig down a little more and found some additional info about white-spaceproperties. I hope it may help someone like me:
上面的答案帮助我解决了我的问题,但我进一步挖掘并找到了一些关于white-space属性的附加信息。我希望它可以帮助像我这样的人:
What is white-spaceproperty:
什么是white-space财产:
white-space is a CSS property that helps control how whitespace and line breaks within an element's text are treated. It can take these values: normal, nowrap, pre, pre-line, pre-wrap.
white-space 是一个 CSS 属性,可帮助控制如何处理元素文本中的空格和换行符。它可以采用以下值:normal、nowrap、pre、pre-line、pre-wrap。


