Javascript CSV parser

var expr = /,(?=(?:[^\"]*\”[^\"]*\”)*(?![^\"]*\”))/g;
var array = str.split(expr);

it works for me

function parseLineCSV(lineCSV) {
// parse csv line by line into array
var CSV = new Array();

// Insert space before character ",". This is to anticipate 'split' in IE
// try this:
// var a=",,,a,,b,,c,,,,d";
// a=a.split(/\,/g);
// document.write(a.length);
// You will see unexpected result!
lineCSV = lineCSV.replace(/,/g," ,");

lineCSV = lineCSV.split(/,/g);

// This is continuing of 'split' issue in IE
// remove all trailing space in each field
for (var i=0;i
<lineCSV.length;i++) {
lineCSV[i] = lineCSV[i].replace(/\s*$/g,"");

var fstart = -1;

for (var i=0;i=0) {
for (var j=fstart+1;j<=i;j++) {
fstart = (lineCSV[i].match(/^"/)) ? i : fstart;

var j=0;

for (var i=0;i
<lineCSV.length;i++) {
if (lineCSV[i]!="-DELETED-") {
CSV[j] = lineCSV[i];
CSV[j] = CSV[j].replace(/^\s*|\s*$/g,""); // remove leading & trailing space
CSV[j] = CSV[j].replace(/^"|"$/g,""); // remove " on the beginning and end
CSV[j] = CSV[j].replace(/""/g,'"'); // replace "" with "

return CSV;

It works for me, I got it from here

Leave a comment

1 Comment

  1. Neither of these methods will parse all valid CSV files correctly. Your regular expression will incorrectly parse any field that contains commas and create two fields instead of one. Fields such as “Last name, First name” are pretty common. Likewise, newlines are valid inside of quoted fields; both methods rely on simply splitting the data on newlines regardless of whether the newline character is inside of a quoted field or not. If you are absolutely sure that none of the data your code will be processing will ever have fields containing commas or newlines it might be faster and easier to just split your string on ‘\n’ and ‘,’. That said if you then reuse it elsewhere where commas and newlines are valid parts of fields you’ll quickly find that your code that “worked” in the past no longer does.

    I recently released a small JavaScript library for dealing with CSV, it correctly handles commas, newlines and double-quotes; if you want to take a look at it you can find it here at

    There’s also a short tutorial on using it on our blog:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: