41

I am using this plugin to parse bbcode bbcodeparser

but it has no functionality to convert \n to <br/>.

I tried adding this:

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

...but it didn't work.

How can I implement line break functionality?

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
user007
  • 3,203
  • 13
  • 46
  • 77

4 Answers4

138

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>
Foreever
  • 7,099
  • 8
  • 53
  • 55
  • edit: Although it says it is unsupported in IE, it seems to work okay in IE8 + 11: http://caniuse.com/#search=white-space – Matt Rowles Jan 16 '15 at 00:01
  • 2
    pre-line will also collapse sequences of whitespaces. If you want to preserve whitespaces, try pre-wrap. There are other options as well: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space?v=example – KayakinKoder May 17 '17 at 02:20
  • I hate when the absolute best answers are at the bottom – Reid Aug 14 '21 at 15:39
15

The above answer helped me to fix my problem but I dig down a little more and found some additional info about white-space properties. I hope it may help someone like me:

What is white-space property:

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.

enter image description here

Rajat Badjatya
  • 760
  • 6
  • 13
3

actually, Browsers doesn't treat \r\n as real new-lines, in PHP nl2br used, where as in Javascript you can use below function for nl2br() equivalent.

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');}
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
Vijay Lathiya
  • 1,087
  • 11
  • 14
2

This worked for me

const regex = /\\n|\\r\\n|\\n\\r|\\r/g;
string.replace(regex, '<br>');