Skip to content

Instantly share code, notes, and snippets.

@vgrichina
Created April 2, 2015 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgrichina/57796fb8d9a8ae41fc0d to your computer and use it in GitHub Desktop.
Save vgrichina/57796fb8d9a8ae41fc0d to your computer and use it in GitHub Desktop.
parse_csv.js
/**
* CSV Parser. Takes a string as input and returns
* an array of arrays (for each row).
*
* @param input String, CSV input
* @param separator String, single character used to separate fields.
* Defaults to ","
* @param quote String, single character used to quote non-simple fields.
* Defaults to "\"".
*/
function parseCSV(input, separator, quote) {
separator = separator || ',';
quote = quote || '"';
// Create your implementation here
var inQuotes = false;
var rows = [];
var row = [];
var value = "";
for (var i = 0; i < input.length; i++) {
var c = input[i];
if (inQuotes) {
if (c == quote) {
if (input[i + 1] != quote) {
inQuotes = false;
} else {
value += quote;
i++;
}
} else {
value += c;
}
} else {
if (c == separator) {
row.push(value);
value = "";
} else if (c == "\n") {
row.push(value);
rows.push(row);
value = "";
row = [];
} else if (c == quote) {
inQuotes = true;
} else {
value += c
}
}
}
row.push(value);
rows.push(row);
return rows;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment