/ Published in: JavaScript
Expand |
Embed | Plain Text
function nl2br(text){ text = escape(text); if(text.indexOf('%0D%0A') > -1){ re_nlchar = /%0D%0A/g ; }else if(text.indexOf('%0A') > -1){ re_nlchar = /%0A/g ; }else if(text.indexOf('%0D') > -1){ re_nlchar = /%0D/g ; } return unescape( text.replace(re_nlchar,'<br />') ); }
Comments
Subscribe to comments
You need to login to post a comment.

The ironic thing about this post is that it itself could use some newline replacement.
\nTried that. Snipplr just didn\'t care whatever I typed. See the \r\n ?
\nSomething has broken with this site.
\nYep, during last night's update I introduced a bug that was messing with newlines. It's been fixed. Sorry about that :)
I've gone through all of the affected snippets and corrected them.
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,'') );
}
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'); }
Um. I take that back. This site strips html and reformats code... pretty silly for a code snippet site. My bad, I apologise.
Or try
str.replace(/([^>\%0D\%0A]?)(\%0D\%0A|%0A\%0D|\%0D|%0A)/g, '$1$2');I had to add this, and then it worked great: