Skip to content

Instantly share code, notes, and snippets.

@Bamuel
Last active October 25, 2023 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bamuel/dce1985471226d62a519c1b91e170da9 to your computer and use it in GitHub Desktop.
Save Bamuel/dce1985471226d62a519c1b91e170da9 to your computer and use it in GitHub Desktop.
ParseCSV Jquery with catching all types of exceptions within the csv file.
function parseCSV(strData, strDelimiter) {
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
var arrData = [[]];
var arrMatches = null;
while (arrMatches = objPattern.exec(strData)) {
var strMatchedDelimiter = arrMatches[1];
if (strMatchedDelimiter.length && strMatchedDelimiter !== strDelimiter) {
arrData.push([]);
}
var strMatchedValue;
if (arrMatches[2]) {
strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"),
"\""
);
} else {
strMatchedValue = arrMatches[3];
}
arrData[arrData.length - 1].push(strMatchedValue);
}
return (arrData);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment