This question already has an answer here:
Does someone have an idea on where I could find some javascript code to parse CSV data ?
This question already has an answer here:
Does someone have an idea on where I could find some javascript code to parse CSV data ?
I have an implementation as part of a spreadsheet project.
This code is not yet tested thoroughly, but anyone is welcome to use it.
As some of the answers noted though, your implementation can be much simpler if you actually have DSV or TSV file, as they disallow the use of the record and field separators in the values. CSV, on the other hand can actually have commas and newlines inside a field, which breaks most regex and split-based approaches.
Here's my PEG(.js) grammar that seems to do ok at RFC 4180 (i.e. it handles the examples at http://en.wikipedia.org/wiki/Comma-separated_values):
Try it out at http://jsfiddle.net/knvzk/10 or http://pegjs.majda.cz/online. Download the generated parser at https://gist.github.com/3362830.
Im not sure why I couldn't kirtans ex. to work for me. It seemed to be failing on empty fields or maybe fields with trailing commas...
This one seems to handle both.
I did not write the parser code, just a wrapper around the parser function to make this work for a file. see Attribution
Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks. There's no splitting or RegEx. It scans the input string 1-2 characters at a time and builds an array.
Test it at http://jsfiddle.net/vHKYH/.
I think I can sufficiently beat Kirtan's answer
Enter jQuery-CSV
It's a jquery plugin designed to work as an end-to-end solution for parsing CSV into Javascript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google Spreadsheed exports (ie mostly involving null values) that the spec is missing.
Example:
Update:
Oh yeah, I should also probably mention that it's completely configurable.
Update 2:
It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same lib.
Update 3:
Since Google Code shutdown, jquery-csv has been migrated to GitHub.
Disclaimer: I am also the author of jQuery-CSV.
Why not just use .split(',') ?
http://www.w3schools.com/jsref/jsref_split.asp