Posted By

cochambre on 08/02/06


Tagged

br


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

meth
nicolaspar


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,'') );
}

You need to login to post a comment.