将字符串转换为数组后,我得到一个错误的数组长度

时间:2014-03-16 14:45:12

标签: javascript regex arrays

在我的浏览器console.log中(由于来自服务器的socket.io回答)我有这个字符串,我需要在数组中进行转换:

'test.tif[0] TIFF 1962x2668+0+0 DirectClass 1-bit 12.8M 0.000u 0:01
 test.tif[1] TIFF 1952x2688+0+0 DirectClass 1-bit 12.8M 0.000u 0:01
 test.tif[2] TIFF 1650x2200+0+0 DirectClass 1-bit 12.8M 0.000u 0:01
 test.tif[3] TIFF 1654x2204+0+0 DirectClass 1-bit 12.8M 0.000u 0:01
 test.tif[4] TIFF 1654x2206+0+0 DirectClass 1-bit 12.8M 0.000u 0:01
 test.tif[5] TIFF 1654x2206+0+0 DirectClass 1-bit 12.8M 0.000u 0:01

                                                                    '

data.split(/(\r\n|\n|\r)/gm);之后

console.log告诉我这个:

 test.tif[0] TIFF 1962x2668+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
,test.tif[1] TIFF 1952x2688+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
,test.tif[2] TIFF 1650x2200+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
,test.tif[3] TIFF 1654x2204+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
,test.tif[4] TIFF 1654x2206+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
,test.tif[5] TIFF 1654x2206+0+0 DirectClass 1-bit 12.8M 0.000u 0:01,
, 

.......附加一个逗号。

当我data.length时,我得到了99的结果。 这怎么可能?获得正确价值的最佳解决方案是什么?

3 个答案:

答案 0 :(得分:2)

看起来您的数据后面有一个额外的换行符,先将其删除 在data = data.replace(/\s$/,"");

之前使用data.split(/(\r\n|\n|\r)/gm);

答案 1 :(得分:2)

  1. 通过在JavaScript中使用组,您可以将匹配的组作为项目包含在拆分结果中。因此,如果您使用(,)这样的正则表达式来分割A,B,则结果为[0] = 'A', [1] = ',', [2] = 'B'
  2. 您可以使用前瞻以确保每个元素后面都有文字,这样您就不会包含任何空白元素。
  3. 正则表达式

    (?:[\r\n]+\s*)+(?=\w)
    

    REY

    上述正则表达式具有修剪任何额外空白区域的优势,在您的情况下可能有点过分。同样[\r\n]+可能被认为是有效的\r\n|\n|\r,因为它将捕获多个连续的中断线以及最初预期的匹配。

答案 2 :(得分:0)

...'因为输入结尾有一个新行。

你可以先拆分

data.trim().split(/(\r\n|\n|\r)/gm);