0

How to convert string to array?

I want to convert a string separated by commas and spaces into Number array in JavaScript.. Ex: "2, 44, -7, 8" -> [ 2, 44, -7, 8 ] And whenever I convert string to array it shows output : [2, 4, 4, NaN, 8]

22nd May 2021, 6:20 AM
Rohan Thakur
Rohan Thakur - avatar
3 Answers
+ 3
var arr = "2, 44, -7, 8".split(/\s*,\s*/).map(s => Number(s));
22nd May 2021, 6:25 AM
visph
visph - avatar
+ 2
I used split() with a regex matching any number of spaces + comma + any number of spaces to act as separator... this return a list of numbers stored as string. then I map that list to another one to convert the strings to numbers ;)
22nd May 2021, 8:05 AM
visph
visph - avatar
0
Can you explain your code? visph
22nd May 2021, 8:01 AM
Rohan Thakur
Rohan Thakur - avatar