Hmahwish
Hmahwish

Reputation: 2232

String with Comma separated numbers to array of integer in javascript

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

Answers (3)

Ghassen Rjab
Ghassen Rjab

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

Beaudinn Greve
Beaudinn Greve

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

leopik
leopik

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

Related Questions