Posted By

cochambre on 08/02/06


Tagged

html replace new line newlines break br


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

meth
nicolaspar
szoftverhiba


Replace newlines with BR (platform safe)


 / Published in: JavaScript
 

  1. function nl2br(text){
  2. text = escape(text);
  3. if(text.indexOf('%0D%0A') > -1){
  4. re_nlchar = /%0D%0A/g ;
  5. }else if(text.indexOf('%0A') > -1){
  6. re_nlchar = /%0A/g ;
  7. }else if(text.indexOf('%0D') > -1){
  8. re_nlchar = /%0D/g ;
  9. }
  10. return unescape( text.replace(re_nlchar,'<br />') );
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Roshambo on August 2, 2006

The ironic thing about this post is that it itself could use some newline replacement.

\n

Posted By: cochambre on August 2, 2006

Tried that. Snipplr just didn\'t care whatever I typed. See the \r\n ?

\n

Posted By: cochambre on August 2, 2006

Something has broken with this site.

\n

Posted By: tylerhall on August 2, 2006

Yep, during last night's update I introduced a bug that was messing with newlines. It's been fixed. Sorry about that :)

Posted By: tylerhall on August 2, 2006

I've gone through all of the affected snippets and corrected them.

Posted By: nickwick76 on August 16, 2009

When the text doesn't contain a newline of any kind, variable 're_nlchar' is not defined and an error is raised when returning from the function.

A suggestion would be to replace the return statement with the following:

if (typeof(renlchar) == "undefined") { return unescape( text ); } else { return unescape( text.replace(renlchar,'') );
}

Posted By: muggo on September 2, 2010

Not only is this really ugly code it doesn't work. nickwicks addition doesn't either.

This isn't much prettier but at least it works

function nl2br (str) {
var breakTag = ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); }

Posted By: muggo on September 2, 2010

Um. I take that back. This site strips html and reformats code... pretty silly for a code snippet site. My bad, I apologise.

Posted By: Emmanuel on November 19, 2010

Or try

str.replace(/([^>\%0D\%0A]?)(\%0D\%0A|%0A\%0D|\%0D|%0A)/g, '$1$2');

Posted By: bradr on September 6, 2012

I had to add this, and then it worked great:

else if (text.indexOf('%5Cr%5Cn') > -1) {
    re_nlchar = /%5Cr%5Cn/g;
}

You need to login to post a comment.