10

I am converting String with Comma separated numbers to a array of integer like,

 var string = "1,2,3,4"; 
 var array = string.replace(/, +/g, ",").split(",").map(Number); 

it returns array = [1,2,3,4];

But when ,

 var string = ""; 
 var array = string.replace(/, +/g, ",").split(",").map(Number); 

it returns array = [0];

I was expecting it to return array = []; can someone say why this is happening.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Hmahwish
  • 2,222
  • 8
  • 26
  • 45

3 Answers3

14

I would recommend this:

var array;
if (string.length === 0) {
    array = new Array();
} else {
    array = string.replace(/, +/g, ",").split(",").map(Number);
}
Ghassen Rjab
  • 683
  • 7
  • 20
4

The string.replace(/, +/g, ",").split(",") returns an array with one item - an empty string. In javascript, empty string when converted to number is 0. See yourself

Number(""); // returns (int)0
leopik
  • 2,323
  • 2
  • 17
  • 29
2

To remove the spaces after the comma you can use regular expressions inside the split function itself.

array = string.split(/\s*,\s*/).map(Number);

I hope it will help

Beaudinn Greve
  • 810
  • 12
  • 17