Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript split add an extra empty array item?

Tags:

javascript

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?

like image 873
alexchenco Avatar asked Feb 08 '23 11:02

alexchenco


1 Answers

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

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();
}
like image 99
Alexander O'Mara Avatar answered Feb 11 '23 01:02

Alexander O'Mara