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
?
This seemed to work in all browsers I tested (safari, opera, chrome, firefox, ie7, ie8, ie9):
http://jsfiddle.net/4bQ5Q/1/
Code: