Skip to content

Instantly share code, notes, and snippets.

@mcshaman
Last active March 28, 2016 09:25
Show Gist options
  • Save mcshaman/0b5d252fb1a0c416e37f to your computer and use it in GitHub Desktop.
Save mcshaman/0b5d252fb1a0c416e37f to your computer and use it in GitHub Desktop.
Light weight CSV paser function that works in old versions of JavaScript
/**
* parseCSV
* Light weight CSV paser function that works in old versions of JavaScript
* @version 1.0.0
* @author McShaman
* @licence MIT
*/
(function(window) {
'use strict';
/**
* The main parser function
* @param {string} dat - CSV data
* @param {Object} ops - Options
* @param {boolean} [ops.headerRow=false] - Items in first row are column headings
* @param {boolean} [ops.strict=false] - Rows must have the same number of columns
*/
window.parseCSV = function(dat, ops){
var fields = [],
rows = [],
headerRow = false,
options = {
headerRow: false,
strict: false
};
for(var property in ops) {
if(options.hasOwnProperty(property)) {
options[property] = ops[property];
}
}
var matches,
match,
pattern = /(?!$)([^\",\r\n]+|\"([^\"]*(\"{2}[^\"]*)*)\"|^)*(,|\r?\n|\r)?/g;
while((matches = pattern.exec(dat))){
if(matches[2]){ // Quote wrapped match found
if(matches[3]) { // Double quoting match found
match = replaceDoubleQuoting(matches[2]);
} else {
match = matches[2];
}
} else { // Unwrapped match found
match = matches[1];
}
fields.push(match);
if(!matches[4] || matches[4] !== ',') {
rows.push(fields);
fields = [];
}
}
if(options.strict) {
if(!rowLengthsEqual(rows)) {
return false;
}
}
if(options.headerRow) {
rows = useFirstRowAsHeaders(rows);
}
return rows;
};
var replaceDoubleQuoting = function(str) {
var pattern = /\"\"/g;
return str.replace(pattern, '"');
};
var rowLengthsEqual = function(arys) {
var equal = arys[0].length;
for(var i = 0, leng = arys.length; i < leng; i++) {
if(arys[i].length !== equal) {
return false;
}
}
return true;
};
var useFirstRowAsHeaders = function(ary) {
var rows = ary.slice(1),
row,
rowsIndex,
rowsLength,
headers = ary[0],
header,
headersIndex,
headersLength,
object,
newArray = [];
for(rowsIndex = 0, rowsLength = rows.length; rowsIndex < rowsLength; rowsIndex++) {
object = {};
row = rows[rowsIndex];
for(headersIndex = 0, headersLength = headers.length; headersIndex < headersLength; headersIndex++) {
header = headers[headersIndex];
object[header] = row[headersIndex];
}
newArray.push(object);
}
return newArray;
};
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment