Skip to content

Instantly share code, notes, and snippets.

@plbowers
plbowers / csvStringToArray.js
Last active September 9, 2022 07:55 — forked from Jezternz/csvStringToArray.js
forked and (1) added header capability and (2) added escaped characters more consistently for https://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data
const csvStringToArray = (strData, header=true) =>
{
//const objPattern = new RegExp(("(\\,|\\r?\\n|\\r|^)(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|([^\\,\\r\\n]*))"),"gi");
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" ), '$1') :
arrMatches[3]);