how to set the text of a pre tag using jquery

Knox picture Knox · Feb 11, 2011 · Viewed 32.1k times · Source

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.)

<pre id="QComment">Initial Text</pre>

at some time later,

$('#QComment').text(databack);   // or
$('#QComment').html(databack);

Answer

Adrian Gonzales picture Adrian Gonzales · Feb 11, 2011

This is a common problem between *nix based systems and windows systems. Someone wrote a simple newline detection plugin for jQuery newlinecharacter

So, what you can do is:

$('#QComment').text(databack.replace(/\r\n/g,EOL));

Which, what you're doing is replacing all windows style line breaks with ones appropriate for the system viewing the data.