EN
JavaScript - convert a string of numbers to an array of numbers
0 points
In this article, we would like to show you how to convert a string of numbers to an array of numbers in JavaScript.
Quick solution (ES6):
xxxxxxxxxx
1
const string = '1,2,3,4';
2
3
const result = string.split(',').map((item) => parseInt(item, 10));
4
5
console.log(result); // [ 1, 2, 3, 4 ]
In this example, we use split()
method to split string
into an array of strings by a comma separator (','
). Then we use map()
method with parseInt()
to convert the array of strings into an array of numbers.
xxxxxxxxxx
1
var string = '1,2,3,4';
2
3
var result = string.split(',').map(function(item) {
4
return parseInt(item, 10);
5
});
6
7
console.log(result); // [ 1, 2, 3, 4 ]
8
console.log(typeof result[0]); // number