How to keep line breaks when using .text() method for jQuery?

You don't need to worry about the HTML entities nor any complex string replacing.

All you need is a little CSS:

#target {
    white-space: pre;
}

and use the .text() approach:

(function(){
    var srcText = $("#src").text().trim();
        i = 0;
        result = srcText[i];
    setInterval(function() {
        if(i == srcText.length-1) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i];
        $("#target").text(result);

    }, 150); // the period between every character and next one, in milliseonds.
})();

http://jsfiddle.net/mattball/vsb9F/


To anyone who's looking for what the title of the question actually asks (this is how I got to this page, "how to keep line breaks when using jQuery's text() method"), you can use something like this:

(function($){
   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
               }
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/<br>/gi,"n").replace(/(<([^>]+)>)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/<br>/gi,"n").replace(/(<([^>]+)>)/gi, "");
            }
         }
   };
})(jQuery);

Now call $('.some-class').innerText() to get the text with line breaks preserved.