Explain Codes LogoExplain Codes Logo

How can I convert a comma-separated string to an array?

javascript
split
string-manipulation
array-conversion
Nikita BarsukovbyNikita Barsukov·Jan 20, 2025
TLDR

Don't break a sweat! Use split(','). Here is how:

var array = "apple,banana,cherry".split(',');

Voila! You have ["apple", "banana", "cherry"].

Leveraging split for conversion

Your weekdays won't be mundane anymore, as split makes converting simple. If you want to tighten up the split, use the limit parameter:

// maybe you only like two fruits var array = "apple,banana,cherry".split(',', 2);

And voila, your fruit salad has just ["apple", "banana"].

Cleaning up messy (spaced and empty) strings

Just like your room, strings can get messy with spaces. But split is there to tidy things:

// extra spaces are like those socks you can't find a pair for var array = "apple, banana, cherry".split(/,\s*/);

Result: ["apple", "banana", "cherry"] - neatly organized!

In the string world, split treats empty values like unwanted clothing:

// closet cleaning time! var array = "apple,,cherry".split(',').filter(Boolean);

All dusted and cleared: ["apple", "cherry"].

Numeric, complex strings and custom functions

What about if you have a numeric string? Just jazz it up using map() and parseInt():

// because a string number is like a beer without foam var numArray = "1,2,3".split(',').map(num => parseInt(num, 10));

And the party goes on with [1, 2, 3]. Mind the second parameter of parseInt(), explaining it would be like telling why beer is best served cold.

For those complex strings with special needs, design a custom function:

function customSplit(input) { // "one ring to rule them all", or in this case, one function! }

This handy function can tackle advanced splitting problems like a JavaScript ninja.

Handling special cases and advanced scenarios

When dealing with finicky strings, employ a few tricks:

  1. Combine split() with regular expressions — to manage pesky spaces and escaped delimiters.
  2. Refine your string pre-split with a brilliant duo - split() and replace().
  3. If you're a fan of JSON-like strings, then JSON.parse() is your secret superpower, following replace().

Ensure that the strings are properly formatted before conversion and sanitize them for security reasons. Trust me, input sanitation is like your insurance policy.