Javascript Preliminary Text with Between Browsers

I have preformatted lines with line breaks and a few spaces, and I want to add them to the node text.

<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 accept as line interrupt:

  • \n breaks lines in all browsers, but in IE (I'm testing for 7) it becomes a space
  • \r breaks lines only in IE
  • \r\n works in all browsers, but in IE the space at the beginning of the second line is terrible.
  • \n\r also normal in all, but in IE the space at the end of the first line is not acceptable for my layout.

I cannot use <br> and innerHTML because IE destroys multidimensional spaces.
jQuery .text(string) has exactly the same behavior .appendChild(createTextNode(string))

How can I insert transitions between browsers?
After all, how can I easily determine if the browser supports \n or \r ?

+7
source share
3 answers

It seemed that this worked in all the browsers I checked (safari, opera, chrome, firefox, ie7, ie8, ie9):

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

the 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);​ 
+7
source

Since IE seems odd, perhaps keep the characters in a variable and conditional comments to change it if 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 fragment seems to display correctly, at least in IE8, so the condition is lt IE 8 .

+4
source

At that time, I found a lighter solution similar to a cross browser:
innerHTML with a rough overlay <pre>

 <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 the only return
\n\r double return

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

+2
source

All Articles