Javascript split () not working in IE

Let's say I have textarea with this text:

  • The first line is some text.
  • second line, another text. The next line will be empty.
  • (empty line)
  • (empty line)
  • last line here

As you can see, lines 3 and 4 are empty ( \n ). I need to get the exact structure of strings (with empty strings) and convert it to an array. Each row is an array element. 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 fine in all browsers except IE. For some reason, the split () function ignores empty lines (3 and 4) in IE. Because of this, they are never passed to an array: s

Squeegy solution in the comments

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

+4
source share
3 answers

Regular expression separation behaves strangely in IE8 and below. Use string comparison instead and it seems to work ( fiddle )

 testText.split("\n") 

but not

 testText.split(/\n/) 

[Edit] From the blog of Stephen Levitan :

Internet Explorer excludes almost all empty values from the resulting array (for example, when two separators appear next to each other in the data or when the separator appears at the beginning or end of the data)

+6
source

Possible JavaScript duplicate : split doesn't work in IE? ? Internet Explorer excludes almost all empty values ​​from the resulting array (for example, when two separators appear next to each other in the data or when the separator appears at the beginning or end of the data).

+2
source

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

 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); } 

A working example is here: http://jsfiddle.net/jfriend00/xQTNZ/ .

+2
source

Source: https://habr.com/ru/post/1386402/


All Articles