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:
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With