Javascript split()在IE中不起作用 [英] Javascript split() not working in IE

查看:612
本文介绍了Javascript split()在IE中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个文本区域,其中包含以下文本:

Lets say I have a textarea with this text:

  1. 第一行输入一些文字.
  2. 第二行,其他文字.下一行将为空.
  3. (空行)
  4. (空行)
  5. 最后一行
  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

如您所见,第3行和第4行为空(\n).我需要获得精确的行结构(以及空行)并将其转换为数组.每行都是数组的元素.这是我当前的代码:

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

它在除IE之外的所有浏览器上都很好用.由于某些原因, split()函数会忽略IE中的空行(3和4).因此,它们永远不会传递到数组:s

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

解决方案

split("\n")替换split(/\n/)-该死的IE!

推荐答案

在IE8及更低版本中,regex拆分行为异常.改用字符串比较,它似乎可以工作(小提琴)

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

testText.split("\n")

而不是

testText.split(/\n/)

来自 Steven Levithan的博客 :

Internet Explorer 从结果中排除几乎所有空值 数组(例如,当两个定界符在 数据,或者在数据的开头或结尾出现定界符时

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)

这篇关于Javascript split()在IE中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆