Simple Javascript code: Transform string of numbers into an array

Norfa Bagas
2 min readOct 6, 2021

At the moment, I’m focusing to learn more about Javascript and NodeJS. I usually use JS for creating API services and some frontend projects. And one of the problems I have faced was to create a function that can accept a string of numbers (or maybe an array of numbers) that is captured from user input, and process it into an array of numbers.

And here is my solution:

I will call it the arrFromStr function. It will receive only 1 parameter in string format and have to return an array of numbers or an empty array if given a null or empty string.

-> arrFromStr("[1, 2, 3, 4]")
<- [1, 2, 3, 4]
-> arrFromStr("[]")
<- []

That’s how our function should behave.

Let’s implement it!

First, we need to create an empty arrFromStr function

const arrFromStr = (str) => {
return str;
}

When dealing with string in javascript, we can use the split function. This function will remove any unused character from the string and will return an array of characters. We can use regular expressions to remove some specific characters. And here is our updated code.

const arrFromStr = (str) => {
return str.split(/[A-Za-z .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/);
}

Now, our input string can be transformed into an array of characters. But, the array returned from the split function also has empty values. We need to remove empty values from the array, and also don’t forget to cast them into an array of numbers.

const arrFromStr = (str) => {
return str
.split(/[A-Za-z .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/)
.filter(str => str)
.map(str => Number(str));
}

Now we already created the function.

How to run the code?
We can test it on a browser console or execute it on the NodeJS terminal.

Here is an example using NodeJS terminal

// use readline for reading user prompt
const readline = require('readline');
// initialize readline object
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const ArrFromStr = (str) => {
return str
.split(/[A-Za-z .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/)
.filter(str => str)
.map(str => Number(str));
}
// user prompt
rl.question("Input the array : ", function (data) {
const arr = ArrFromStr(data);
console.log(`Array: ${arr}`);
rl.close();
});
rl.on('close', function () {
process.exit(0);
})

Save the code on your chosen folder, open a terminal and run node your_file.js

Example output:

$  node your_file.js
-> Input the array : [1, 2, 3, 4]
-> Array: [ 1, 2, 3, 4 ]

--

--

Norfa Bagas

Software engineer. I also do some research related to Computer Vision and Artificial Intelligence