-2

I'm a js beginner and want convert a string e.g. "1, 4, 7" to an array [1, 4, 7].

I need something like the opposite of the function join

Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
DNS
  • 7
  • 3

4 Answers4

2

Try this:

const convert = str => str.split(',').map(p=>+p)

console.log(convert("1, 4, 7"))
Bill Cheng
  • 856
  • 7
  • 9
0
 >> "1, 4, 7".split(", ").map(num => +num)
 >> [1, 4, 7]
JamieT
  • 1,177
  • 8
  • 19
0

Try

let s = "1, 4, 7";

let a = JSON.parse(`[${s}]`);

console.log(a);
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
0

var str = '1, 2, 3'; var = str.split(", ");

by splitting the string, it will be return as an array missing the delimiter... in this case ", " (comma and space)

this will not work as expected if str = '1,2, 3';

for that you will need a regular expression... var = str.split(/, ?/);

aequalsb
  • 3,405
  • 1
  • 19
  • 21