views:

655

answers:

3

I'm trying to split the innerText of a div on the newlines in the source for it. This works fine with:

$('div').text().split("\r\n|\r|\n")

But this fails in IE 7, due to the newlines apparently being stripped out. jQuery 1.3.2 doesn't appear to be at fault since i also tried both:

$('div')[0].innerText.split("\r\n|\r|\n")

and

$('div')[0].innerHTML.split("\r\n|\r|\n")

Neither do any of the above work if i change the div to a pre.

It appears that the newlines are once the source is parsed into the DOM. :( Is this so? Is there no way to get at them with javascript?

+2  A: 

Try splitting on "\n" instead of "\r\n".

To do both, consider splitting on the pattern "\r?\n".

Jason Cohen
I've tried on \n, \r, \r\n|\r|\n, and other things that should work. It's not the regex, i'm pretty sure.
Nathan Bubna
+1  A: 

Newlines are whitespace, and are not generally preserved. They mean the same thing as a space does.

John Saunders
A: 

IE does lose newlines in element content, except:

  • in pre (and plaintext, not that that's ever used this century)
  • in textarea, where it also adds spurious ‘\r’s that don't count towards its own character-counting mechanisms

However, regardless of that, this won't work:

split("\r\n|\r|\n")

JavaScript's String.split, in contrast to Java's, takes a simple delimiter string, not a regex pattern.

bobince