Javascript preformatted text with cross-browser line breaks

5.2k views Asked by At

I have preformatted strings with line-breaks and multi-spaces and I want to append them into a text node.

<pre id="bar"></pre>

<script>
   var string = "Preformatted"
                + "\n"  // \r, \r\n, \n\r or what else?
                + "multispace     string";
   var text = document.createTextNode(string);
   document.getElementById('bar').appendChild(text);
</script>

I tried to adopt as line breaker:

  • \n breaks lines in all browsers, but in IE (I'm testing on 7) becomes a space
  • \r breaks lines only in IE
  • \r\n works in all browser but in IE the space at beginning of second line is horror
  • \n\r also ok in all, but in IE the space at the end of first line is inacceptable for my layout.

I can't use <br> and innerHTML because IE collapses multi-spaces.
jQuery .text(string) has exactly the same behavior of .appendChild(createTextNode(string))

How can I insert cross-browser line breaks?
Eventually, how can I easily detect if a browser supports \n or \r ?

3

There are 3 answers

3
Esailija On BEST ANSWER

This seemed to work in all browsers I tested (safari, opera, chrome, firefox, ie7, ie8, ie9):

http://jsfiddle.net/4bQ5Q/1/

Code:

var textarea = document.createElement("textarea");
textarea.value = "\n";
var eol = textarea.value.replace(/\r\n/, "\r");

var string = "Preformatted" + eol + "multispace     string";

var text = document.createTextNode(string);
document.getElementById('bar').appendChild(text);​
1
Jonathan Lonowski On

Since IE seems to be odd one out, perhaps store the characters in a variable and use conditional comments to change it as necessary:

<script> var $LF = '\n'; </script>
<!--[if lt IE 8]>
    <script> $LF = '\r'; </script>
<![endif]-->

<script>
  var string = "Preformatted"
               + $LF
               + "multispace     string";
  var text = document.createTextNode(string);
  document.getElementById('bar').appendChild(text);
</script>

Your snippet does seem to display properly in at least IE8, thus the lt IE 8 condition.

0
Salvador On

In the meanwhile I found an easier solution that seems to be cross-browser:
innerHTML with a brute <pre> imposition

<div id="bar"></div>

<script>
  var string = "Preformatted \n"
             + "string \r"
             + "with \r\n"
             + "assorted \n\r"
             + "line   breaks";
  document.getElementById('bar').innerHTML = "<pre>"+string+"</pre>";
</script>

\r\n becomes a single return
\n\r double return

Imperfection: IE 10 compatibility mode 7 add a space at the end of final line.