Lets say we have a comma separated string value.
let commaSepratedStringValues = '1,2,3,4,5'; console.log(typeof commaSepratedStringValues); // output: string
Now we want to separate all the numbers and convert it into array. For this purpose we will have to use built-in method of string called split() which takes an argument of string. In this argument we have to pass a separator character so split() method can divide our string based on that character. For our case we will pass , (comma) as argument.
This is how our code will look like
let commaSepratedStringValues = '1,2,3,4,5'; let arrayOfValues = commaSepratedStringValues.split(','); console.log(arrayOfValues); // output: [1, 2, 3, 4, 5]
The answer is pretty simple. We have to pass (space) as argument to our split() method.
This is how our code will look like for this case
let spaceSepratedStringValues = '1 2 3 4 5'; let arrayOfValues = spaceSepratedStringValues.split(' '); console.log(arrayOfValues); // output: [1, 2, 3, 4, 5]
This is how our example code will look like
let commaSepratedStringValues = '1,2,3,4,5'; let arrayOfValues = JSON.parse('[' + commaSepratedStringValues + ']'); console.log(arrayOfValues); // output: [1, 2, 3, 4, 5]