JavaScript split add an extra empty array item? - Stack Overflow

The following code reads a file and turned each line into array items:fs.readFile('en.txt', &

The following code reads a file and turned each line into array items:

fs.readFile('en.txt', 'utf8', function (err, data) {
  if (err) {
    return console.log(err)
  }

  enStrings = data.split(/[\r\n]+/g)
}

en.txt looks like this:

Line 1
Line 2
Line 3

But I'm puzzled. console.log(enStrings) outputs this:

[ 'Line 1', 'Line 2', 'Line 3', '' ]

Why is that last empty item being added? And how to remove it?

The following code reads a file and turned each line into array items:

fs.readFile('en.txt', 'utf8', function (err, data) {
  if (err) {
    return console.log(err)
  }

  enStrings = data.split(/[\r\n]+/g)
}

en.txt looks like this:

Line 1
Line 2
Line 3

But I'm puzzled. console.log(enStrings) outputs this:

[ 'Line 1', 'Line 2', 'Line 3', '' ]

Why is that last empty item being added? And how to remove it?

Share Improve this question asked Nov 26, 2015 at 6:45 wycwyc 55.4k83 gold badges256 silver badges441 bronze badges 1
  • Since you are splitting by the new line character it is understandable that there would be an empty line marking the end of the file. You may need to explicitly remove the empty line after reading the file. – CalebB Commented Nov 26, 2015 at 6:53
Add a ment  | 

3 Answers 3

Reset to default 7

This would happen if your text file has a trailing new line character, which is mon.

Why not trim before splitting?

enStrings = data.trim().split(/[\r\n]+/g);

Alternately, you could remove just the trailing new line characters before splitting.

enStrings = data.replace(/[\n\r]+$/, '').split(/[\r\n]+/g)

However, if your data is long, you may want to avoid the performance hit of recreating the entire string before splitting. If that is the case, you could use the following to pop it off the end.

if (enStrings.length && !enStrings[enStrings.length-1]) {
    enStrings.pop();
}

You may use filter:

console.log(enStrings.filter(Boolean));

Empty strings are falsy value so using .filter(Boolean) will only list the truthy value and removes the empty strings from your array.

You can try this:

enStrings = data.split(/[\r\n]+/g);
enStrings.splice($.inArray('', enStrings), 1);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745307314a4621789.html

相关推荐

  • JavaScript split add an extra empty array item? - Stack Overflow

    The following code reads a file and turned each line into array items:fs.readFile('en.txt', &

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信