Javascript split() not working in IE

2019-02-24 07:35发布

问题:

Lets say I have a textarea with this text:

  1. first line some text.
  2. second line, other text. next line will be empty.
  3. (empty line)
  4. (empty line)
  5. last line here

As you can see, lines 3 and 4 are empty (\n). I need to get the exact lines structure (with empty lines as well) and convert it to an array. Each line is an element of the array. This is my current code:

var lines = $('#q').val().split(/\n/);
alert(lines.length); //using alert() because IE doesn't support console.log()
var texts = [];
for(i = 0; i < lines.length; i++) {
    texts.push($.trim(encodeURIComponent(lines[i])));
}

It works great on all browsers, except IE. For some reason, the split() function ignores empty lines (3 and 4) in IE. Because of that, they are never passed into the array :s

Solution by Squeegy in the comments

Replace split(/\n/) with split("\n") - damn you IE!

回答1:

The regex split is behaving strangely in IE8 and lower. Use a string comparison instead and it seems to work (fiddle)

testText.split("\n")

rather than

testText.split(/\n/)

[Edit] From Steven Levithan's Blog:

Internet Explorer excludes almost all empty values from the resulting array (e.g., when two delimiters appear next to each other in the data, or when a delimiter appears at the start or end of the data)



回答2:

Possible duplicate of JavaScript: split doesn't work in IE? ? Internet Explorer excludes almost all empty values from the resulting array (e.g., when two delimiters appear next to each other in the data, or when a delimiter appears at the start or end of the data).



回答3:

I see the same screwy behavior in IE with .split() and new lines. You can use your own split function to control it more closely:

function mySplit(str, ch) {
    var pos, start = 0, result = [];
    while ((pos = str.indexOf(ch, start)) != -1) {
        result.push(str.substring(start, pos));
        start = pos + 1;
    }
    result.push(str.substr(start));
    return(result);    
}

Working example here: http://jsfiddle.net/jfriend00/xQTNZ/.