Skip to content

Instantly share code, notes, and snippets.

@basith374
Created July 16, 2021 11:02
Show Gist options
  • Save basith374/b8a5a682e48089804a2ded869cd070e7 to your computer and use it in GitHub Desktop.
Save basith374/b8a5a682e48089804a2ded869cd070e7 to your computer and use it in GitHub Desktop.
Split CSV row using javascript
function splitRow(row) {
const cols = [];
while (row.length) {
let commaIdx = row.indexOf(",");
const quoteIdx = row.indexOf("\"");
if(quoteIdx > -1 && commaIdx > quoteIdx) {
commaIdx = row.slice(1).indexOf("\"") + 2;
}
const stripQuote = (str) => {
return str[0] === "\"" && str[str.length - 1] === "\"" ? str.slice(1, str.length - 1) : str
}
cols.push(stripQuote(row.slice(0, commaIdx === -1 ? row.length : commaIdx)))
row = row.slice(commaIdx === -1 ? row.length : commaIdx + 1)
}
return cols;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment