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?
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?
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>
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.
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');}
$1
and $2
refers to the first and second group in the regexp (a group is something in ()
). So the code will retain the original parts of the string and just insert <br>
tags before a new line.
May 19, 2014 at 11:43
This worked for me
const regex = /\\n|\\r\\n|\\n\\r|\\r/g;
string.replace(regex, '<br>');
str = str.replace(/\n/g, '<br />');
str.replace(/\r\n|\n|\r/gm, '<br />');