JSFiddle - React, Tailwind, and code Playground
JavaScript
function displayMatrix(array){
var s = [];
//For simplicity, quotes aren't escaped. Purely display, though.
for(var i=0; i<array.length; i++){
s[i] = "['" + array[i].join("', '") + "']";
}
return "[" + s.join("], [") + "]";
}
alert(displayMatrix(CSVToArray('"a, comma","2","3"')));
function CSVToArray( strData, strDelimiter ){
// Properly escape the delimiter, if existent.
// If no delimiter is given, use a comma
strDelimiter = (strDelimiter || ",").replace(/([[^$.|?*+(){}])/g, '\\$1');
//What are the quotation characters? "'
var quotes = "\"'";
// Create a regular expression to parse the CSV values.
// match[1] = Contains the delimiter if the RegExp is not at the begin
// match[2] = quote, if any
// match[3] = string inside quotes, if match[2] exists
// match[4] = non-quoted strings
var objPattern = new RegExp(
// Delimiter or marker of new row
"(?:(" + strDelimiter + ")|[\\n\\r]|^)" +
// Quoted fields
"(?:([" + quotes + "])((?:[^" + quotes + "]+|(?!\\2).|\\2\\2)*)\\2" +
// Standard fields
"|([^" + quotes + strDelimiter + "\\n\\r]*))"
, "gi");
// Create a matrix (2d array) to hold data, which will be returned.
var arrData = [];
// Execute the RegExp until no match is found
var arrMatches;
while ( arrMatches = objPattern.exec( strData ) ){
// If the first group of the RegExp does is empty, no delimiter is
// matched. This only occurs at the beginning of a new row
if ( !arrMatches[ 1 ] ){
// Add an empty row to our data array.
arrData.push( [] );
}
var quote = arrMatches[ 2 ]
if ( quote ){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 3...