Created
September 23, 2018 01:39
-
-
Save Jezternz/c8e9fafc2c114e079829974e3764db75 to your computer and use it in GitHub Desktop.
reduced size and added fix for https://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data
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
const csvStringToArray = strData => | |
{ | |
const objPattern = new RegExp(("(\\,|\\r?\\n|\\r|^)(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|([^\\,\\r\\n]*))"),"gi"); | |
let arrMatches = null, arrData = [[]]; | |
while (arrMatches = objPattern.exec(strData)){ | |
if (arrMatches[1].length && arrMatches[1] !== ",")arrData.push([]); | |
arrData[arrData.length - 1].push(arrMatches[2] ? | |
arrMatches[2].replace(new RegExp( "\"\"", "g" ), "\"") : | |
arrMatches[3]); | |
} | |
return arrData; | |
} |
Suggestion to fix the problem with empty cells being parsed as undefined (and some cleanup):
const csvStringToArray = (data) => {
const re = /(,|\r?\n|\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^,\r\n]*))/gi
const result = [[]]
let matches
while ((matches = re.exec(data))) {
if (matches[1].length && matches[1] !== ',') result.push([])
result[result.length - 1].push(
matches[2] !== undefined ? matches[2].replace(/""/g, '"') : matches[3]
)
}
return result
}
The core fix is in your line 7, though, as arrMatches[2]
may be undefined
, ''
, or something truthy. And you want the empty string to also go down the first code path, since in that case arrMatches[3]
is undefined
.
What exactly is the condition for breaking out of this while statement?
What exactly is the condition for breaking out of this while statement?
When arrMatches value is no longer truthy. aka when RegExp.exec (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) returns null instead of a value.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What an awesome little code snippet!