Example JavaScript code to parse CSV data

前端 未结 12 1761
梦谈多话
梦谈多话 2020-11-21 07:58

Where could I find some JavaScript code to parse CSV data?

12条回答
  •  走了就别回头了
    2020-11-21 08:48

    Regular expressions to the rescue! These few lines of code handle properly quoted fields with embedded commas, quotes, and newlines based on the RFC 4180 standard.

    function parseCsv(data, fieldSep, newLine) {
        fieldSep = fieldSep || ',';
        newLine = newLine || '\n';
        var nSep = '\x1D';
        var qSep = '\x1E';
        var cSep = '\x1F';
        var nSepRe = new RegExp(nSep, 'g');
        var qSepRe = new RegExp(qSep, 'g');
        var cSepRe = new RegExp(cSep, 'g');
        var fieldRe = new RegExp('(?<=(^|[' + fieldSep + '\\n]))"(|[\\s\\S]+?(? '; // newline representation in case a field contains newlines, default: '\n' 
    var grid = parseCsv(csv, separator, newline);
    // expected: [ [ 'A1', 'B1', 'C1' ], [ 'A "2"', 'B, 2', 'C 
    2' ] ]

    You don't need a parser-generator such as lex/yacc. The regular expression handles RFC 4180 properly thanks to positive lookbehind, negative lookbehind, and positive lookahead.

    Clone/download code at https://github.com/peterthoeny/parse-csv-js

提交回复
热议问题