Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript preformatted text with cross-browser line breaks

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 ?

like image 365
Salvador Avatar asked Jun 04 '12 19:06

Salvador


2 Answers

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);​
like image 149
Esailija Avatar answered Sep 21 '22 20:09

Esailija


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.

like image 35
Jonathan Lonowski Avatar answered Sep 17 '22 20:09

Jonathan Lonowski