How can I parse a CSV string with Javascript, which contains comma in data?

javascript splitting a comma-separated string but ignoring commas in quotes
convert comma separated string to array javascript
javascript split string by comma
csv string example
how to get comma separated values in javascript
javascript csv parser
convert comma separated string to array c#
javascript csv to array

I have the following type of string

var string = "'string, duppi, du', 23, lala"

I want to split the string into an array on each comma, but only the commas outside the single quotation marks.

I cant figure out the right regex for the split...

string.split(/,/)

will give me

["'string", " duppi", " du'", " 23", " lala"]

but the result should be:

["string, duppi, du", "23", "lala"]

is there any cross browser solution?

Split a string by commas but ignore commas within double-quotes , Here is a JavaScript function to do it: function splitCSVButIgnoreCommasInDoublequotes(str) { //split the str first //then merge the elments between commas added when turning the array into a string and the actual captured values. For anyone interested, the first part matches double​-quoted, comma-delimited arguments:. How can I parse a CSV string with Javascript, which contains comma in data? 14 answers Does someone have an idea on where I could find some javascript code to parse CSV data ? Here's an extremely simple CSV parser that handles quoted fields with commas, new lines, and escaped double quotation marks.

RFC 4180 solution

This does not solve the string in the question since its format is not conforming with RFC 4180; the acceptable encoding is escaping double quote with double quote. The solution below works correctly with CSV files d/l from google spreadsheets.

UPDATE (3/2017)

Parsing single line would be wrong. According to RFC 4180 fields may contain CRLF which will cause any line reader to break the CSV file. Here is an updated version that parses CSV string:

'use strict';

function csvToArray(text) {
    let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;
    for (l of text) {
        if ('"' === l) {
            if (s && l === p) row[i] += l;
            s = !s;
        } else if (',' === l && s) l = row[++i] = '';
        else if ('\n' === l && s) {
            if ('\r' === p) row[i] = row[i].slice(0, -1);
            row = ret[++r] = [l = '']; i = 0;
        } else row[i] += l;
        p = l;
    }
    return ret;
};

let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"\r\n"2nd line one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"';
console.log(csvToArray(test));

How to Convert Comma Separated String into an Array in JavaScript, How to Convert Comma Separated String into an Array in JavaScript You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty Accessing individual values EDIT: To answer your question literally, if you are looking to simply grab values separated by commas (CSV) then this would work: [code]var array = string.split(',');[/code] Although, as pointed out by Daniel Couper, if you are looking for a s

I liked FakeRainBrigand's answer, however it contains a few problems: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I tried editing his answer but my edit got rejected by reviewers that apparently did not understand my code. Here is my version of FakeRainBrigand's code. There is also a fiddle: http://jsfiddle.net/xTezm/46/

String.prototype.splitCSV = function() {
        var matches = this.match(/(\s*"[^"]+"\s*|\s*[^,]+|,)(?=,|$)/g);
        for (var n = 0; n < matches.length; ++n) {
            matches[n] = matches[n].trim();
            if (matches[n] == ',') matches[n] = '';
        }
        if (this[0] == ',') matches.unshift("");
        return matches;
}

var string = ',"string, duppi, du" , 23 ,,, "string, duppi, du",dup,"", , lala';
var parsed = string.splitCSV();
alert(parsed.join('|'));

How to parse a CSV string with Javascript, by commas (CSV) then this would work: [code]var array = string.split(',');[/code] are looking for a solution to a string that might contain commas in the values,  Can someone tell me how to generate a CSV file and handle the case when values contain comma in them. Between comma as seperater and comma as part of data. Creating CSV file where values contain comma (Java in General forum at Coderanch)

PEG(.js) grammar that handles RFC 4180 examples at http://en.wikipedia.org/wiki/Comma-separated_values:

start
  = [\n\r]* first:line rest:([\n\r]+ data:line { return data; })* [\n\r]* { rest.unshift(first); return rest; }

line
  = first:field rest:("," text:field { return text; })*
    & { return !!first || rest.length; } // ignore blank lines
    { rest.unshift(first); return rest; }

field
  = '"' text:char* '"' { return text.join(''); }
  / text:[^\n\r,]* { return text.join(''); }

char
  = '"' '"' { return '"'; }
  / [^"]

Test at http://jsfiddle.net/knvzk/10 or https://pegjs.org/online.

Download the generated parser at https://gist.github.com/3362830.

Ask Ben: Parsing CSV Strings With Javascript Exec() Regular , Create a regular expression to parse the CSV values. for example, to include commas and/or line feeds in the field values of the CSV file. I have also faced same type of problem when I have to parse a CSV File. The File contains a column Address which contains the ',' . After parsing that CSV to JSON I get mismatched mapping of the keys while converting it into JSON File. I used node for parsing the file and Library like baby parse and csvtojson Example of file -

I had a very specific use case where I wanted to copy cells from Google Sheets into my web app. Cells could include double-quotes and new-line characters. Using copy and paste, the cells are delimited by a tab characters, and cells with odd data are double quoted. I tried this main solution, the linked article using regexp, and Jquery-CSV, and CSVToArray. http://papaparse.com/ Is the only one that worked out of the box. Copy and paste is seamless with Google Sheets with default auto-detect options.

Convert comma separated string to array using JavaScript , A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and  If you are creating the import CSV in Excel, the quotation marks will be inserted automatically by Excel whenever a comma is detected in any cell - Saving the CSV in Excel and opening the same in Notepad reveals the enclosing quotation marks for cells containing commas. improve this answer. edited May 22 '13 at 12:40. answered May 22 '13 at 12:33.

JavaScript to parse a CSV string and create JSON objects based on , JavaScript to parse a CSV string and create JSON objects based on the column headers. gistfile1.txt var data = [], i = 0, k = 0, header = []; arrays. The default delimiter is the comma, but this Check to see if the given delimiter has a length. Splitting comma separated string, ignore commas in quotes, but allow strings with one double quotation. but seems more applicable here (but useful over there) In my application I'm parsing a csv so my split credential is ",". this method I suppose only works for where you have a single char split argument.

How to handle double quotes (") and comma (,) in a field of CSV, Error: You don't have JavaScript enabled. This tool Some times in one field data might have double quotes (") or comma(,). By checking optional double quoutes I could handle comma in a string but it field has double quotes its creating an issue. Can any one This way Informatica will parse the .CSV file  /** * CSVToArray parses any String of Data including '\r' ' ' characters, * and returns an array with the rows of data. * @param {String} CSV_string - the CSV string you need to parse * @param {String} delimiter - the delimeter used to separate fields of data * @returns {Array} rows - rows of CSV where first row are column headers */ function

Reading and Writing CSV Files with Node.js, The term CSV is an abbreviation that stands for comma-separated values. A CSV file is a plain text file that contains data formatted according to the CSV of helpful modules that could handle generating or parsing the CSV content for us. NOTE: I concocted this solution before I was reminded about all the “special cases” that can occur in a valid CSV file, like escaped quotes. I’m leaving my answer for those who want something quick and dirty, but I recommend Evan’s answer for accuracy.

Comments
  • Is it always single-quotes? Is there ever a single-quote inside a quoted string? If so, how is it escaped (backslash, doubled-up)?
  • What if the quote characters are completely interchangeable between double and single quote characters as in JavaScript and HTML/XML code? If so then this requires a more extensive parsing operation that CSV.
  • actually yes, there could be a single quote inside, escaping with backslash would be fine.
  • Can a value be a double quoted string?
  • Papa Parse does a fine job. Parsing a Local CSV File with JavaScript and Papa Parse: joyofdata.de/blog/…
  • @Evan Plaice - Thanks for the nice words. Sure you can use any separator. Just replace every comma in my regex with the separator of choice (but the separator cannot be whitespace). Cheers.
  • @Evan Plaice - You are welcome to use any of my regexes for any purpose you desire. A note of recognition would be nice but not necessary. Good luck with your plug-in. Cheers!
  • Cool, here's the project code.google.com/p/jquery-csv. Eventually, I want to add an extension format to CSV called SSV (Structured Separated Values) which is simply CSV with metadata (ie, delimiter, separator, line ending, etc) included.
  • Thanks a lot for this great implementation - I used it as the basis for a Node.js module (csv-iterator).
  • I applaud the detail and clarify of your answer, but it should be noted somewhere that your definition of CSV does not fit RFC 4180 which is the closes thing there is to a standard for CSV, and which I can say anecdotally is commonly used. In particular this would be the normal way to "escape" a double quote character within a string field: "field one", "field two", "a ""final"" field containing two double quote marks" I have not tested Trevor Dixon's answer on this page, but it is an answer which addresses the RFC 4180 definition of CSV.
  • This should be ranked much higher, never try to roll your own CSV parser, it will not work correctly - especially when using regexes. Papaparse is awesome -- use it!
  • If i read my file in via fileReader and my result: Id, Name, Age 1, John Smith, 65 2, Jane Doe, 30 how can i parse based on columns i specify?
  • After you get the 2d array, remove the first index (it those are your prop names), then iterate over the rest of the array, creating objects with each of the values as a property. It'll look like this: [{Id: 1, Name: "John Smith", Age: 65}, {Id: 2, Name: "Jane Doe", Age: 30}]
  • Hmm, your regexp does have some issues: It can not handle whitespace between a quote and a comma, and does not support 2 consecutive commas. I've updated your answer with code that fixes both issues and made a new fiddle: jsfiddle.net/xTezm/43