Created
July 16, 2021 11:02
-
-
Save basith374/b8a5a682e48089804a2ded869cd070e7 to your computer and use it in GitHub Desktop.
Split CSV row using javascript
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
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