javascript nl2br
After many torments while finding a working nl2br() javascript function, i came accross this idea…
For those that are not familiar with the nl2br function from PHP, this simply converts regular line breaks (carriage return ASCII characters) to HTML breaks.
The function converts to XHTML format: <br />
Here is the code:
text=escape(text);
return unescape(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,‘<br />’));
}
The function uses regular expressions to find all carriage return occurrences.
This can be \r\n or \n\r or \r or \n.
Why escape and unescape? Just because on a text with quotes the regular expression crashes. To be sure everything will be ok, i’ve escaped all special characters and then return the unescaped HTML-break-based content.
To preserve unicode characters you must use urlEncodeComponent and urlDecodeComponent instead of escape and unescape.
Support for these functions was added with javascript 1.5, so only modern browsers would know about this.
The function may look like this:
if(urlEncodeComponent){
text=urlEncodeComponent(text);
return urlEncodeComponent(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,‘<br />’));
}
else{
text=escape(text);
return unescape(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,‘<br />’));
}
}
replace was introduced in javascript 1.2 as far as I know…
Have fun using this snippet…
Lucian Sabo
|
Tech stuff (english)
|
07 24th, 2007
|
3 People have left comments on this post
correct me if I’m wrong – the script works better (at least for me) this way though…
“encodeURIComponent”
function nl2br(text){
if(encodeURIComponent){
text=encodeURIComponent(text);
return decodeURIComponent(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,”));
}
else{
text=escape(text);
return unescape(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,”));
}
}
text.replace takes two arguments: needle and replacement string.
You have deleted the second parameter. I don’ know what you intended, but this:
1. probably causes an error
2. doesn’t serves the purpose of nl2br. Nl2Br means replacing new line break (\n,\r\n, \n\r, etc) with the line break HTML tag (br)
So your script in the best scenario will strip all line breaks.
I had to add %0A to the regex in order to replace correctly