Explain Codes LogoExplain Codes Logo

How to split a comma separated string using JavaScript?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Feb 21, 2025
TLDR

The good news is you can split a comma-separated string using .split(',') method:

const fruits = "apple,orange,banana".split(','); console.log(fruits); // ["apple", "orange", "banana"] // Look, Mum, no commas!

Hey, and we can trim whitespace around elements while we're at it:

const fruits = " apple , orange , banana ".split(',').map(fruit => fruit.trim()); console.log(fruits); // ["apple", "orange", "banana"] // Hey, this banana isn't squashed!

Things worth paying attention to

Vanishing empty strings

Look how cheeky empty strings appear when commas play "sandwich":

const colors = "red,,blue".split(','); console.log(colors); // ["red", "", "blue"] // Is there a color that's kind of... nothing?

Not a big fan of emptiness? Use .filter(Boolean) to get rid of them:

const colors = "red,,blue".split(',').filter(Boolean); console.log(colors); // ["red", "blue"] // Red and blue, that's better, less existential crisis!

Controlling the roster with a split limit

You can use the limit parameter to control the split. Here only two best of the four:

const data = "one,two,three,four".split(',', 2); console.log(data); // ["one", "two"] // Sorry three and four, it's not us, it's you.

Delimiter patterns as diverse as life itself

Ensure you use regular expressions for splitting when delimiters come in different styles:

const mixDelimited = "One, Two and Three; Four".split(/[,;] */); console.log(mixDelimited); // ["One", "Two and Three", "Four"] // Embrace diversity, they said!

Next level complexities

Handling the curiosities of quotations

When dealing with quoted data, you probably want to keep the integrity of quoted contents:

const quoted = '"apple","orange","banana", "kiwi"'; const preserved = quoted.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g); console.log(preserved); // ["apple", "orange", "banana", "kiwi"] // Even fruits have their secrets!

Dealing with the beast of CSV data

CSV data is often a complex beast because of internal commas. Simple .split(',') can get scared:

const csvData = 'John Doe, "New York, NY", 30'; // Ouch, .split(',') just split New York, NY into two. That's not right!

In such cases, use tried-and-tested libraries like PapaParse or simply negative lookahead in your regex patterns to split the data accurately.