I'm using a pre tag to hold some raw formated text that has carriage returns. When the page is first displayed, it looks fine. Later, I want to refresh just the pre data. I've tried two ways to do this with jquery, one using .html() and the other way with .text(). Both sorta work, but the .html throws away the carriage returns and the .text double spaces the carriage returns! I've also tried .val() but that didn't work at all. Here's the code (of course I only use one of the jquery lines at a time.)

yes, very good point about the content having \r\n in it. But the intial text also has \r\n in it. Let me investigate a bit further.
–
KnoxFeb 11 '11 at 19:23

1

The replace as written above is incorrect. It won't replace more than a single instance. Use databack.replace(/\r\n/g, '\n') to replace all instances of \r\n with a single \n.
–
coreywardFeb 11 '11 at 19:32

Coreyward was right and zzzzBov was on the right track, but his suggestion only replaces the first \r\n. :)
–
KnoxFeb 11 '11 at 19:51

I would rather not bother typing twice as much. Trying to optimize out jQuery selectors is about as useful as writing code in assembly instead of PHP or Java - it makes a difference when something is inside a loop that will run a million times, but it is a waste of time otherwise.
–
TgrFeb 11 '11 at 19:27

@zzzz What if jQuery is already loaded into the page (for other purposes)? You are assuming that the OP is using jQuery just for this one thing.
–
Šime VidasFeb 11 '11 at 19:28

@Sime Vidas, not at all. I apologize that I was unclear, I'm not saying to not use jquery at all, I'm saying to not use it in this instance. No jQuery code is necessary because it's so simple. The "jQuery overhead" i was referring to is the creation of a new jQuery object just for the purpose of unboxing the object to access its innerHTML property.
–
zzzzBovFeb 11 '11 at 19:36

@zzzz According to my test case, document.getElementById('foo').innerHTML = txt; takes 9.5ms to execute, whereas $('#foo').text(txt); takes 24.4ms to execute. Therefore, the performance gain is around 15 milliseconds. Why would anyone write twice as much code just to have a 15ms gain? Sounds most unreasonable to me.
–
Šime VidasFeb 11 '11 at 19:48