Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
@JoshuaKimsey

This comment has been minimized.

Copy link

@JoshuaKimsey JoshuaKimsey commented Mar 25, 2020

What an awesome little code snippet!

@ygra

This comment has been minimized.

Copy link

@ygra ygra commented Sep 17, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment