Losing newlines in div content in IE 7
-
06-07-2019 - |
Question
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?
Solution
Newlines are whitespace, and are not generally preserved. They mean the same thing as a space does.
OTHER TIPS
Try splitting on "\n"
instead of "\r\n"
.
To do both, consider splitting on the pattern "\r?\n"
.
IE does lose newlines in element content, except:
- in
pre
(andplaintext
, 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.