How to split a comma separated string using JavaScript?
The good news is you can split a comma-separated string using .split(',')
method:
Hey, and we can trim whitespace around elements while we're at it:
Things worth paying attention to
Vanishing empty strings
Look how cheeky empty strings appear when commas play "sandwich":
Not a big fan of emptiness? Use .filter(Boolean)
to get rid of them:
Controlling the roster with a split limit
You can use the limit parameter to control the split. Here only two best of the four:
Delimiter patterns as diverse as life itself
Ensure you use regular expressions for splitting when delimiters come in different styles:
Next level complexities
Handling the curiosities of quotations
When dealing with quoted data, you probably want to keep the integrity of quoted contents:
Dealing with the beast of CSV data
CSV data is often a complex beast because of internal commas. Simple .split(',')
can get scared:
In such cases, use tried-and-tested libraries like PapaParse or simply negative lookahead in your regex patterns to split the data accurately.
Was this article helpful?