Created
April 2, 2015 16:01
-
-
Save vgrichina/57796fb8d9a8ae41fc0d to your computer and use it in GitHub Desktop.
parse_csv.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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