-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
  • 85,173
  • 29
  • 368
  • 345
DNS
  • 7
  • 3

4 Answers4

2

Try this:

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

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

Try

let s = "1, 4, 7";

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

console.log(a);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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,765
  • 1
  • 20
  • 21