Convert a String to Array of Numbers in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read


Photo by Joshua Earle

Convert a String to Array of Numbers #

To convert a string to array of numbers:

  1. Call the split() method on the string, to get an array of strings.
  2. Use the map() method to iterate over the array and convert each string to number.
  3. The map method will return a new array, that contains only numbers.
const str = '5,15,45'; // ๐Ÿ‘‡๏ธ ['5', '15', '45'] const arrOfStr = str.split(','); const arrOfNum = => { return Number(element); }); console.log(arrOfNum); // ๐Ÿ‘‰๏ธ [5, 15, 45]

The only parameter we passed to the String.split method is a separator.

In this example, the numbers are separated by a comma in the string, however they could be separated by a space or any other character.
const str = '5 15 45'; // ๐Ÿ‘‡๏ธ ['5', '15', '45'] console.log(str.split(' '));
If your numbers are separated by another character(s) in the string, pass the character(s) as a parameter to the split method.
const str = '5-15-45'; // ๐Ÿ‘‡๏ธ ['5', '15', '45'] console.log(str.split('-'));

The final step is to call the method on the array of strings.

The function we passed to the map method gets called with each element (string) in the array.

On each iteration, we convert the string into a number and return the result.

The map method returns a new array that contains only the values that the function returned - in our case all the numbers.

If your string contains numbers that end with characters, e.g. 15a, you have to use the parseInt method.

const str = '5a,15b,45c'; // ๐Ÿ‘‡๏ธ ['5a', '15b', '45c'] const arrOfStr = str.split(','); const arrOfNum = => { return parseInt(element, 10); }); console.log(arrOfNum); // ๐Ÿ‘‰๏ธ [5, 15, 45]

Because our numbers end with a character, we can't pass them straight to the Number object. Instead, we use the parseInt method to extract the numbers.

We pass the following parameters to the parseInt method:

  • a string we want to parse into a number
  • the radix, the default radix is not 10, so we have to explicitly specify it

Note that this approach only works if the number precedes the characters, it wouldn't work if you had a string like a15,b30.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee