THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
This tutorial explains multiple ways the string contains numbers into an array of numbers for example. 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 output
[ 9, 21, 12, 8 ]
There are multiple ways.
Iterate the array using map() and convert the number 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 and with split array and number object.
Here is an example.
let array=Array.from(strNumbers.split(','), Number)
console.log(array)
In a summary, Multiple ways to convert a string of numbers into an array of numbers with examples.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts