Update: This has now been solved. Thanks, David!
I'm having a problem with splitting a string into lines in Javascript. An initial test is at 1.html.
Firefox and Opera do what's expected, but IE is doing something … bizzare.
I'm trying to go after this text:
<pre><code id="test">Here is some sample text. Above this is a blank line. And below this is another one. And below this one are two more. That concludes our demonstration.</code></pre>
With this Javascript:
window.onload = function() {
var element = document.getElementById("test")
var text= element.innerHTML;
var lines = text.split(/\r\n|\r|\n/);
var s = "";
for (var i = 0; i < lines.length; i++) {
s += (i + 1) + ": " + lines[i] + "\n";
}
alert(s);
};
This is the output from Opera and Firefox:
1: Here is some sample text. 2: 3: Above this is a blank line. 4: And below this is another one. 5: 6: And below this one are two more. 7: 8: 9: That concludes our demonstration.This is what I get from IE:
1: Here is some sample text.Above this is a blank line. 2: And below this is another one.And below this one are two more. 3: That concludes our demonstration.
One interesting change is if I remove the <code>
block and put the id directly
on the <pre>
element, which I try in 2.html. Firefox and
Opera both still do as expected, but IE responds with:
1: Here is some sample text. 2: Above this is a blank line. 3: And below this is another one. 4: And below this one are two more. 5: That concludes our demonstration.
In this case, IE splits the lines correctly, but ignores blank lines. I really want to be able
to go after the <code>
element, and I need the blank lines too, so this is only
marginally helpful.
I'm going to post a question to the smart people on the WDF-DOM mailing list. Further updates will be posted here when I find more information.
David Gale posted a response that pointed
me in the right direction. The innerHTML
property is changing the source text. When I replaced it
with childNodes[0].data
, I cleaned up the really bizzare behavior. I still needed to add another
several lines to clear up the fact that IE doesn't return the empty tokens in the String:split method, but that
was relatively straightforward now that this other is working. The new code is at 3.html and looks
like this:
window.onload = function() {
var element = document.getElementById("test")
// var text= element.innerHTML;
var text= element.childNodes[0].data;
text = text.replace(/(\r\n|\r|\n)(\r\n|\r|\n)/g, "$1 $2");
var lines = text.split(/\r\n|\r|\n/);
var s = "";
for (var i = 0; i < lines.length; i++) {
if (lines[i] == " ") lines[i] = "";
s += (i + 1) + ": " + lines[i] + "\n";
}
alert(s);
};
Thanks, David!