How to convert a string to an array of numbers in JavaScript?

This tutorial explains multiple ways to convert a string containing numbers into an array of numbers.

You can check my other post on Javascript check substring exists in a String

For example, a String contains numbers with delimiter

var strNumbers = "9,21,12,8";

The string contains numbers delimited by a comma.

And the output converted to Array

[ 9, 21, 12, 8 ]

How to convert a string to an array of numbers in JavaScript?

There are multiple ways.

  • use the map array function

First, the String of numbers is split using the split() function, which returns an Array of Strings.

Iterate the array using map(), and convert the string using parseInt with base 10

let arrayNumbers = strNumbers.split(",").map(function (strNumber) {
  return parseInt(strNumber, 10);
});

The same can be simplified using ES6 arrow functions

let arrayNumbers = strNumbers
  .split(",")
  .map((strNumber) => parseInt(strNumber, 10));
  • use Array from function

Pass the result of String.split function(),

Array.from() function, used to create an array from existing arrays.

An array of Strings is converted to a number array with a Number class format for conversion. Here is an example.

let array = Array.from(strNumbers.split(","), Number);
console.log(array);
  • Use Regular expression We can easily convert a String to an Array of numbers.
var strNumbers = "9,21,12,8";
const strArray = strNumbers.match(/\d+/g);
console.log(strArray) // ["9", "21", "12", "8"]

const arrayNumber = strArray?.map(Number);
console.log(arrayNumber) //[9, 21, 12, 8]

In Example above,

  • Regular expression used(/\d+/g).\d represents digits 0-9, \d+ indicates matches with one or more digits, /g is a Global search
  • The match function in the array returns all the matched numbers, It returns the array of Strings.
  • Convert this string array to a number array using the map() function with the Number class.

Conclusion

In summary, Multiple ways to convert a string of numbers into an array of numbers with examples.