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