1

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!

5
  • what browser are you using? Commented May 4, 2014 at 15:20
  • Google Chrome, latest Commented May 4, 2014 at 15:21
  • cannot be reproduced in google chrome Version 34.0.1847.131 Commented May 4, 2014 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""] Commented May 4, 2014 at 15:25
  • update your question? Commented May 4, 2014 at 15:29

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

5 Comments

I just realized because it's going through cookies, when I just do .split(",") I get this: [""215", " 216", " 217""]
Need to get rid of that surrounding quotes within the array
s.split(",").map(function(item){ return item.match(/\d+/)})
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)
it seems @MohamedElMahallawy just did it in that way :)

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.