Skip to content

Instantly share code, notes, and snippets.

@gmac
Last active December 17, 2015 13:59
Show Gist options
  • Save gmac/5620847 to your computer and use it in GitHub Desktop.
Save gmac/5620847 to your computer and use it in GitHub Desktop.
CSV Parser
function parseCSV(csv, delimiter) {
delimiter = (delimiter || ",");
var pattern = new RegExp("(\\"+ delimiter +"|\\r?\\n|\\r|^)"+"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|"+"([^\"\\"+ delimiter +"\\r\\n]*))", "gi");
var quote = new RegExp("\"\"", "g");
var data = [[]];
var matches = null;
var val, d;
while (matches = pattern.exec(csv)) {
d = matches[ 1 ];
if (d.length && (d !== delimiter)) data.push([]);
val = matches[ 2 ] ? matches[ 2 ].replace(quote, "\"") : matches[ 3 ];
data[ data.length-1 ].push(val);
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment