Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following array:

s = "215, 216, 217" 

When I do

s.split(",").map(Number)

I am getting this back:

[NaN, 216, NaN] 

If s has only two numbers, both return as NaN. Help!

Update:

Got it fixed! I had to get rid of quotes that surrounded the string because I was getting it from a cookie.

s.replace(/\"/g, "").split(",").map(Number)

did the trick!

Thanks!

share|improve this question
    
what browser are you using? –  Ejay May 4 at 15:20
    
Google Chrome, latest –  Mohamed El Mahallawy May 4 at 15:21
    
cannot be reproduced in google chrome Version 34.0.1847.131 –  Ejay May 4 at 15:23
    
Actually, I am doing it through cookies and realized my array when I do split(",") on the string I get this: [""215", " 216", " 217""] –  Mohamed El Mahallawy May 4 at 15:25
    
update your question? –  Ejay May 4 at 15:29

1 Answer 1

This will explains it:

s.split(",").map(function(item){ return item.trim() }).map(Number)

There are space between the numbers:

s = "215,/* here */ 216,/* here */ 217" 

Other possible solutions

s.replace(/\s/g,'').split(',').map(Number)

or what it seems was the initial approach but using Regular Expression to get rid of the extra space:

s.split(/\s*,\s*/).map(Number)
share|improve this answer
    
I just realized because it's going through cookies, when I just do .split(",") I get this: [""215", " 216", " 217""] –  Mohamed El Mahallawy May 4 at 15:28
    
Need to get rid of that surrounding quotes within the array –  Mohamed El Mahallawy May 4 at 15:28
1  
s.split(",").map(function(item){ return item.match(/\d+/)}) –  Ejay May 4 at 15:31
    
thanks @Ejay I was trying to make a point although your option is very valid. I was also thinking about s.replace(/\s/g,'').split(',').map(Number) –  Dalorzo May 4 at 15:34
    
it seems @MohamedElMahallawy just did it in that way :) –  Dalorzo May 4 at 15:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.