Reputation: 2232
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.
Upvotes: 10
Views: 10809
Reputation: 713
I would recommend this:
var array;
if (string.length === 0) {
array = new Array();
} else {
array = string.replace(/, +/g, ",").split(",").map(Number);
}
Upvotes: 14
Reputation: 820
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
Upvotes: 2
Reputation: 2351
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
Upvotes: 4