Languages
[Edit]
EN

JavaScript - convert string with commas to array

0 points
Created by:
Majid-Hajibaba
972

In this article, we would like to show you how to convert string with commas to array in JavaScript.

1. Convert string to array of strings

In this example, we use split() method with comma (',') as separator to split string with commas into array of strings.

// ONLINE-RUNNER:browser;

var text = '1,2,3';

var array = text.split(',');

console.log(array); // [ '1', '2', '3' ]

2. Convert string to array of numbers

In this example, we additionally use map() method to convert all elements from the splitted array into Number type.

// ONLINE-RUNNER:browser;

var text = '1,2,3';

var array = text.split(',').map(Number);

console.log(array); // [ 1, 2, 3 ]

 

See also

  1. JavaScript - split string

  2. JavaScript - convert string array to integer array

References

  1. String.prototype.split() - JavaScript | MDN
  2. Map - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join