A function to parse CSV contents with multiline support in JavaScript
// Copyright Robert Eisele 2016
function parseCSV(cont, sep = ',', quot = '"') {
const ret = [];
let field = "";
let inStr = false;
let row = [];
for (var i = 0; i < cont.length; i++) {
const c = cont[i];
if (inStr) {
if (c === quot) {
inStr = false;
} else {
field += c;
}
if (i == cont.length - 1 && (row.length > 0 || field !== "")) {
row.push(field.trim());
field = "";
ret.push(row);
row = [];
}
} else if (c === quot) {
inStr = true;
} else if (c === sep) {
row.push(field.trim());
field = "";
} else if (c === "\n" || c === "\r" || i == cont.length - 1) {
if (row.length > 0 || field !== "") {
row.push(field.trim());
field = "";
ret.push(row);
row = [];
}
} else {
field += c;
}
}
return ret;
}
Or install it directly using NPM:
npm install @raw/parsecsv