Skip to content

Instantly share code, notes, and snippets.

@defbyte
Forked from gmac/csv-parser
Last active December 17, 2015 15:19
Show Gist options
  • Save defbyte/5630654 to your computer and use it in GitHub Desktop.
Save defbyte/5630654 to your computer and use it in GitHub Desktop.
Require module of Greg's CSV Parser
/*
Parse CSV Function
Thanks to Greg MacWilliam:
https://gist.github.com/gmac/5620847#file-csv-parser
*/
define('parse-csv', function (){
var parseCSV = (function( root ) {
return 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;
};
}(this));
return parseCSV;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment