views:

725

answers:

2

I'm having jQuery take some textarea content and insert it into an li.

I want it to visually retain the line breaks.

There must be a really simple way to do this...

+2  A: 

you can simply do:

textAreaContent=textAreaContent.replace(/\n/g,"<br>");
mck89
Cheers, this kind of worked, except it would treat multiple line breaks as a single line break.
gbhall
I've updated it and now it uses a regexp so if you want to treat multiple line breaks as a single br change the regexp with: /\n+/g
mck89
Thank you. Hopefully someone will find your answer useful, but the function below works as well. I feel kind of bad that you're making more effort, but a function is more desirable.
gbhall
+2  A: 
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');
}
aSeptik
Thank you this works perfectly. Odd how this isn't an official function of jQuery.
gbhall
cause jQuery is not meant to replace native javascript function like replace, it is focused on CSS selector chaining and easy access! maybe in future version;-)
aSeptik