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.

4
  • you forget replace after string. Commented Apr 21, 2015 at 11:35
  • 1
    .split() always returns at least one element. Commented Apr 21, 2015 at 11:35
  • 1
    Edited, So I suppose I have to add a check whether string is empty or not then only split it . Commented Apr 21, 2015 at 11:39
  • related: How to convert comma separated string into numeric array in javascript Commented Jun 22, 2022 at 20:19

3 Answers 3

14

I would recommend this:

var array;
if (string.length === 0) {
    array = new Array();
} else {
    array = string.replace(/, +/g, ",").split(",").map(Number);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thx RGraham, exactly what I wanted. (my first answer)
As according to this answer I ended up doing --> array = (string.length === 0) ? new Array() : string.replace(/, +/g, ",").split(",").map(Number);
much more elegant (y)
It looks like you are missing the 'replace': array = string.replace(/, +/g, ",").split(",").map(Number);
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

2 Comments

you forget replace after string same as OP.
Ya I got that now .Thanks
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.