Nathan Bubna
Nathan Bubna

Reputation: 6933

Losing newlines in div content in IE 7

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?

Upvotes: 2

Views: 1345

Answers (3)

bobince
bobince

Reputation: 536379

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.

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

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

Upvotes: 1

Jason Cohen
Jason Cohen

Reputation: 83021

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

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

Upvotes: 2

Related Questions