如何使用Javascript解析CSV字符串,其中包含数据中的逗号?

时间:2021-09-25 17:02:05

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?

有没有跨浏览器解决方案?

14 个解决方案

#1


171  

Disclaimer

2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does NOT fit the RFC 4180 definition of CSV and it also does NOT fit MS Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.

2014-12-01更新:以下答案仅适用于一种非常特定的CSV格式。正如DG在评论中正确指出的那样,此解决方案不符合RFC 4180的CSV定义,也不适合MS Excel格式。此解决方案简单地演示了如何解析包含混合字符串类型的一个(非标准)CSV输入行,其中字符串可能包含转义引号和逗号。

A non-standard CSV solution

As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.

正如austincheney正确指出的那样,如果你想正确处理可能包含转义字符的带引号的字符串,你真的需要从头到尾解析字符串。此外,OP没有明确定义“CSV字符串”究竟是什么。首先,我们必须定义什么构成有效的CSV字符串及其各个值。

Given: "CSV String" Definition

For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:

出于本讨论的目的,“CSV字符串”由零个或多个值组成,其中多个值由逗号分隔。每个值可能包括:

  1. A double quoted string. (may contain unescaped single quotes.)
  2. 双引号字符串。 (可能包含未转义的单引号。)

  3. A single quoted string. (may contain unescaped double quotes.)
  4. 单引号字符串。 (可能包含未转义的双引号。)

  5. A non-quoted string. (may NOT contain quotes, commas or backslashes.)
  6. 未引用的字符串。 (不得包含引号,逗号或反斜杠。)

  7. An empty value. (An all whitespace value is considered empty.)
  8. 空值。 (所有空白值都被视为空。)

Rules/Notes:

  • Quoted values may contain commas.
  • 带引号的值可能包含逗号。

  • Quoted values may contain escaped-anything, e.g. 'that\'s cool'.
  • 引用的值可能包含转义任何内容,例如'这很酷'。

  • Values containing quotes, commas, or backslashes must be quoted.
  • 必须引用包含引号,逗号或反斜杠的值。

  • Values containing leading or trailing whitespace must be quoted.
  • 必须引用包含前导或尾随空格的值。

  • The backslash is removed from all: \' in single quoted values.
  • 在单引号值中从所有:\'中删除反斜杠。

  • The backslash is removed from all: \" in double quoted values.
  • 反斜杠从所有:\“中删除双引号值。

  • Non-quoted strings are trimmed of any leading and trailing spaces.
  • 任何前导和尾随空格都会修剪非引用字符串。

  • The comma separator may have adjacent whitespace (which is ignored).
  • 逗号分隔符可以具有相邻的空格(被忽略)。

Find:

A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.

一种JavaScript函数,用于将有效的CSV字符串(如上所述)转换为字符串值数组。

Solution:

The regular expressions used by this solution are complex. And (IMHO) all non-trivial regexes should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regex syntax (expressed using Python's handy: r'''...''' raw-multi-line-string syntax).

此解决方案使用的正则表达式很复杂。而且(恕我直言)所有非平凡的正则表达式都应该以*间隔模式呈现,并带有大量的注释和缩进。不幸的是,JavaScript不允许*间隔模式。因此,此解决方案实现的正则表达式首先以本机正则表达式语法呈现(使用Python的方便表达:r''''''''raw-multi-line-string语法)。

First here is a regular expression which validates that a CVS string meets the above requirements:

首先是一个正则表达式,它验证CVS字符串是否满足上述要求:

Regex to validate a "CSV string":

re_valid = r"""# Validate a CSV string having single, double or un-quoted values.^                                   # Anchor to start of string.\s*                                 # Allow whitespace before value.(?:                                 # Group for value alternatives.  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.)                                   # End group of value alternatives.\s*                                 # Allow whitespace after value.(?:                                 # Zero or more additional values  ,                                 # Values separated by a comma.  \s*                               # Allow whitespace before value.  (?:                               # Group for value alternatives.    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.  )                                 # End group of value alternatives.  \s*                               # Allow whitespace after value.)*                                  # Zero or more additional values$                                   # Anchor to end of string."""

If a string matches the above regex, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regex. The following regex is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).

如果字符串与上述正则表达式匹配,则该字符串是有效的CSV字符串(根据前面所述的规则),并且可以使用以下正则表达式进行解析。然后使用以下正则表达式匹配CSV字符串中的一个值。重复应用它,直到找不到更多匹配项(并且已解析所有值)。

Regex to parse one value from valid CSV string:

re_value = r"""# Match one value in valid CSV string.(?!\s*$)                            # Don't match empty last value.\s*                                 # Strip whitespace before value.(?:                                 # Group for value alternatives.  '([^'\\]*(?:\\[\S\s][^'\\]*)*)'   # Either $1: Single quoted string,| "([^"\\]*(?:\\[\S\s][^"\\]*)*)"   # or $2: Double quoted string,| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)  # or $3: Non-comma, non-quote stuff.)                                   # End group of value alternatives.\s*                                 # Strip whitespace after value.(?:,|$)                             # Field ends on comma or EOS."""

Note that there is one special case value that this regex does not match - the very last value when that value is empty. This special "empty last value" case is tested for and handled by the js function which follows.

请注意,此正则表达式不匹配有一个特殊情况值 - 该值为空时的最后一个值。这个特殊的“空的最后值”情况由下面的js函数测试和处理。

JavaScript function to parse CSV string:

// Return array of string values, or NULL if CSV string not well formed.function CSVtoArray(text) {    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;    // Return NULL if input string is not well formed CSV string.    if (!re_valid.test(text)) return null;    var a = [];                     // Initialize array to receive values.    text.replace(re_value, // "Walk" the string using replace with callback.        function(m0, m1, m2, m3) {            // Remove backslash from \' in single quoted values.            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));            // Remove backslash from \" in double quoted values.            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));            else if (m3 !== undefined) a.push(m3);            return ''; // Return empty string.        });    // Handle special case of empty last value.    if (/,\s*$/.test(text)) a.push('');    return a;};

Example input and output:

In the following examples, curly braces are used to delimit the {result strings}. (This is to help visualize leading/trailing spaces and zero-length strings.)

在以下示例中,花括号用于分隔{result strings}。 (这有助于可视化前导/尾随空格和零长度字符串。)

// Test 1: Test string from original question.var test = "'string, duppi, du', 23, lala";var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {string, duppi, du}    a[1] = {23}    a[2] = {lala} */
// Test 2: Empty CSV string.var test = "";var a = CSVtoArray(test);/* Array hes 0 elements: */
// Test 3: CSV string with two empty values.var test = ",";var a = CSVtoArray(test);/* Array hes 2 elements:    a[0] = {}    a[1] = {} */
// Test 4: Double quoted CSV string having single quoted values.var test = "'one','two with escaped \' single quote', 'three, with, commas'";var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {one}    a[1] = {two with escaped ' single quote}    a[2] = {three, with, commas} */
// Test 5: Single quoted CSV string having double quoted values.var test = '"one","two with escaped \" double quote", "three, with, commas"';var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {one}    a[1] = {two with escaped " double quote}    a[2] = {three, with, commas} */
// Test 6: CSV string with whitespace in and around empty and non-empty values.var test = "   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  ";var a = CSVtoArray(test);/* Array hes 8 elements:    a[0] = {one}    a[1] = {two}    a[2] = {}    a[3] = { four}    a[4] = {}    a[5] = {six }    a[6] = { seven }    a[7] = {} */

Additional notes:

This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is NOT valid:

此解决方案要求CSV字符串为“有效”。例如,未加引号的值可能不包含反斜杠或引号,例如以下CSV字符串无效:

var invalid1 = "one, that's me!, escaped \, comma"

This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for: "Comma Separated Values".

这不是真正的限制,因为任何子字符串都可以表示为单引号或双引号。另请注意,此解决方案仅代表一种可能的定义:“逗号分隔值”。

Edit: 2014-05-19: Added disclaimer.Edit: 2014-12-01: Moved disclaimer to top.

编辑次数:2014-05-19:已添加免责声明。编辑:2014-12-01:将免责声明移至顶部。

#2


23  

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.

这不解决问题中的字符串,因为它的格式不符合RFC 4180;可接受的编码是双引号双引号。以下解决方案可正确使用谷歌电子表格中的CSV文件d / l。

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:

解析单行是错误的。根据RFC 4180字段可能包含CRLF,这将导致任何行读取器中断CSV文件。这是一个解析CSV字符串的更新版本:

'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));

OLD ANSWER

(Single line solution)

(单线解决方案)

function CSVtoArray(text) {    let ret = [''], i = 0, p = '', s = true;    for (let l in text) {        l = text[l];        if ('"' === l) {            s = !s;            if ('"' === p) {                ret[i] += '"';                l = '-';            } else if ('' === p)                l = '-';        } else if (s && ',' === l)            l = ret[++i] = '';        else            ret[i] += l;        p = l;    }    return ret;}let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,five for fun';console.log(CSVtoArray(test));

And for the fun, here is how you create CSV from the array:

为了好玩,以下是从阵列创建CSV的方法:

function arrayToCSV(row) {    for (let i in row) {        row[i] = row[i].replace(/"/g, '""');    }    return '"' + row.join('","') + '"';}let row = [  "one",  "two with escaped \" double quote",  "three, with, commas",  "four with no quotes (now has)",  "five for fun"];let text = arrayToCSV(row);console.log(text);

#3


6  

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

在http://en.wikipedia.org/wiki/Comma-separated_values处理RFC 4180示例的PEG(.js)语法:

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.

在http://jsfiddle.net/knvzk/10或https://pegjs.org/online进行测试。

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

通过https://gist.github.com/3362830下载生成的解析器。

#4


3  

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/

我喜欢FakeRainBrigand的答案,但是它包含一些问题:它不能处理引号和逗号之间的空格,并且不支持2个连续的逗号。我尝试编辑他的答案,但我的编辑遭到了显然不理解我的代码的审稿人的拒绝。这是我的FakeRainBrigand代码版本。还有一个小提琴: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('|'));

#5


2  

If you can have your quote delimiter be double-quotes, then this is a duplicate of JavaScript Code to Parse CSV Data.

如果您可以将引号分隔符设置为双引号,则这是JavaScript代码与解析CSV数据的副本。

You can either translate all single-quotes to double-quotes first:

您可以先将所有单引号翻译为双引号:

string = string.replace( /'/g, '"' );

...or you can edit the regex in that question to recognize single-quotes instead of double-quotes:

...或者您可以编辑该问题中的正则表达式以识别单引号而不是双引号:

// Quoted fields."(?:'([^']*(?:''[^']*)*)'|" +

However, this assumes certain markup that is not clear from your question. Please clarify what all the various possibilities of markup can be, per my comment on your question.

但是,这假定某些标记在您的问题中不明确。请根据我对您的问题的评论,澄清标记的各种可能性。

#6


2  

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.

我有一个非常具体的用例,我想将Google表格中的单元格复制到我的网络应用程序中。单元格可以包含双引号和换行符。使用复制和粘贴,单元格由制表符分隔,带有奇数数据的单元格是双引号。我尝试了这个主要的解决方案,链接的文章使用regexp,Jquery-CSV和CSVToArray。 http://papaparse.com/是唯一一个开箱即用的产品。使用默认的自动检测选项,Google表格可以无缝复制和粘贴。

#7


1  

My answer presumes your input is a reflection of code/content from web sources where single and double quote characters are fully interchangeable provided they occur as an non-escaped matching set.

我的回答假设您的输入是来自Web源代码/内容的反映,其中单引号和双引号字符完全可互换,前提是它们作为非转义匹配集出现。

You cannot use regex for this. You actually have to write a micro parser to analyze the string you wish to split. I will, for the sake of this answer, call the quoted parts of your strings as sub-strings. You need to specifically walk across the string. Consider the following case:

你不能使用正则表达式。实际上你必须编写一个微解析器来分析你想要分割的字符串。为了这个答案,我会将字符串的引用部分称为子字符串。你需要专门走过这个字符串。考虑以下情况:

var a = "some sample string with \"double quotes\" and 'single quotes' and some craziness like this: \\\" or \\'",    b = "sample of code from JavaScript with a regex containing a comma /\,/ that should probably be ignored.";

In this case you have absolutely no idea where a sub-string starts or ends by simply analyzing the input for a character pattern. Instead you have to write logic to make decisions on whether a quote character is used a quote character, is itself unquoted, and that the quote character is not following an escape.

在这种情况下,通过简单地分析字符模式的输入,您完全不知道子字符串的开始或结束位置。相反,您必须编写逻辑来决定引用字符是否使用引号字符,本身是否未引用,以及引号字符是否跟随转义。

I am not going to write that level of complexity of code for you, but you can look at something I recently wrote that has the pattern you need. This code has nothing to do with commas, but is otherwise a valid enough micro-parser for you to follow in writing your own code. Look into the asifix function of the following application:

我不打算为你编写那么复杂的代码,但你可以看看我最近编写的具有你需要的模式的东西。此代码与逗号无关,但在其他方面是一个有效的微解析器,您可以在编写自己的代码时遵循。查看以下应用程序的asifix函数:

https://github.com/austincheney/Pretty-Diff/blob/master/fulljsmin.js

#8


1  

People seemed to be against RegEx for this. Why?

人们似乎反对RegEx。为什么?

(\s*'[^']+'|\s*[^,]+)(?=,|$)

Here's the code. I also made a fiddle.

这是代码。我也做了一个小提琴。

String.prototype.splitCSV = function(sep) {  var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;  return matches = this.match(regex);    }var string = "'string, duppi, du', 23, 'string, duppi, du', lala";var parsed = string.splitCSV();alert(parsed.join('|'));

#9


1  

While reading csv to string it contain null value in between string so try it \0 Line by line it works me.

在读取csv到字符串时,它在字符串之间包含空值,所以试试它\ 0逐行它对我有用。

stringLine = stringLine.replace( /\0/g, "" );

#10


1  

To complement this answer

补充这个答案

If you need to parse quotes escaped with another quote, example:

如果您需要解析使用其他引号转义的引号,例如:

"some ""value"" that is on xlsx file",123

You can use

您可以使用

function parse(text) {  const csvExp = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|"([^""]*(?:"[\S\s][^""]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;  const values = [];  text.replace(csvExp, (m0, m1, m2, m3, m4) => {    if (m1 !== undefined) {      values.push(m1.replace(/\\'/g, "'"));    }    else if (m2 !== undefined) {      values.push(m2.replace(/\\"/g, '"'));    }    else if (m3 !== undefined) {      values.push(m3.replace(/""/g, '"'));    }    else if (m4 !== undefined) {      values.push(m4);    }    return '';  });  if (/,\s*$/.test(text)) {    values.push('');  }  return values;}

#11


1  

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 -

当我必须解析CSV文件时,我也遇到了同样的问题。文件包含一个包含','的列地址。在将该CSV解析为JSON后,我将密钥映射不匹配,同时将其转换为JSON文件。我使用node解析文件和库像baby parse和csvtojson文件示例 -

address,pincodefoo,baar , 123456

While I was parsing directly without using baby parse in JSON I was getting

虽然我直接解析而没有使用JSON中的婴儿解析,但我得到了

[{ address: 'foo', pincode: 'baar', 'field3': '123456'}]

So I wrote a code which removes the comma(,) with any other deliminatorwith every field

所以我写了一个代码,用每个字段删除逗号(,)与任何其他分隔符

/* csvString(input) = "address, pincode\\nfoo, bar, 123456\\n" output = "address, pincode\\nfoo {YOUR DELIMITER} bar, 123455\\n"*/const removeComma = function(csvString){    let delimiter = '|'    let Baby = require('babyparse')    let arrRow = Baby.parse(csvString).data;    /*      arrRow = [       [ 'address', 'pincode' ],      [ 'foo, bar', '123456']      ]    */    return arrRow.map((singleRow, index) => {        //the data will include         /*         singleRow = [ 'address', 'pincode' ]        */        return singleRow.map(singleField => {            //for removing the comma in the feild            return singleField.split(',').join(delimiter)        })    }).reduce((acc, value, key) => {        acc = acc +(Array.isArray(value) ?         value.reduce((acc1, val)=> {            acc1 = acc1+ val + ','            return acc1        }, '') : '') + '\n';        return acc;    },'')}

The function returned can be passed into csvtojson library and thus result can be used.

返回的函数可以传递给csvtojson库,因此可以使用结果。

const csv = require('csvtojson')let csvString = "address, pincode\\nfoo, bar, 123456\\n"let jsonArray = []modifiedCsvString = removeComma(csvString)csv()  .fromString(modifiedCsvString)  .on('json', json => jsonArray.push(json))  .on('end', () => {    /* do any thing with the json Array */  })
Now You can get the output like

[{  address: 'foo, bar',  pincode: 123456}]

#12


0  

According to this blog post, this function should do it:

根据这篇博文,这个函数应该这样做:

String.prototype.splitCSV = function(sep) {  for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {    if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {      if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {        foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");      } else if (x) {        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));      } else foo = foo.shift().split(sep).concat(foo);    } else foo[x].replace(/''/g, "'");  } return foo;};

You would call it like so:

你会这样称呼它:

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

This jsfiddle kind of works, but it looks like some of the elements have spaces before them.

这种jsfiddle类型的工作,但看起来有些元素在它们之前有空格。

#13


0  

Aside from the excellent and complete answer from ridgerunner, I thought of a very simple workaround for when your backend runs php.

除了来自ridgerunner的优秀而完整的答案之外,我想到了一个非常简单的解决方法,当你的后端运行php时。

Add this php file to your domain's backend (say: csv.php)

将此php文件添加到域的后端(例如:csv.php)

<?phpsession_start(); //optionalheader("content-type: text/xml");header("charset=UTF-8");//set the delimiter and the End of Line character of your csv content:echo json_encode(array_map('str_getcsv',str_getcsv($_POST["csv"],"\n")));?>

Now add this function to your javascript toolkit (should be revised a bit to make crossbrowser I believe.)

现在将此函数添加到您的javascript工具包中(我应该稍微修改一下以制作crossbrowser。)

function csvToArray(csv) {    var oXhr = new XMLHttpRequest;    oXhr.addEventListener("readystatechange",            function () {                if (this.readyState == 4 && this.status == 200) {                    console.log(this.responseText);                    console.log(JSON.parse(this.responseText));                }            }    );    oXhr.open("POST","path/to/csv.php",true);    oXhr.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");    oXhr.send("csv=" + encodeURIComponent(csv));}

Will cost you 1 ajax call, but at least you won't duplicate code nor include any external library.

将花费你1 ajax调用,但至少你不会重复代码,也不包括任何外部库。

Ref: http://php.net/manual/en/function.str-getcsv.php

#14


0  

You can use papaparse.js like the example bellow:

您可以像下面的示例一样使用papaparse.js:

<!DOCTYPE html><html lang="en"><head>    <title>CSV</title></head><body>    <input type="file" id="files" multiple="">    <button onclick="csvGetter()">CSV Getter</button>    <h3>The Result will be in the Console.</h3><script src="papaparse.min.js"></script><script>     function csvGetter() {        var file = document.getElementById('files').files[0];        Papa.parse(file, {            complete: function(results) {                console.log(results.data);                }           });        }  </script>

Don't Forget to include papaparse.js in the same folder.

不要忘记将papaparse.js包含在同一个文件夹中。

#1


171  

Disclaimer

2014-12-01 Update: The answer below works only for one very specific format of CSV. As correctly pointed out by DG in the comments, this solution does NOT fit the RFC 4180 definition of CSV and it also does NOT fit MS Excel format. This solution simply demonstrates how one can parse one (non-standard) CSV line of input which contains a mix of string types, where the strings may contain escaped quotes and commas.

2014-12-01更新:以下答案仅适用于一种非常特定的CSV格式。正如DG在评论中正确指出的那样,此解决方案不符合RFC 4180的CSV定义,也不适合MS Excel格式。此解决方案简单地演示了如何解析包含混合字符串类型的一个(非标准)CSV输入行,其中字符串可能包含转义引号和逗号。

A non-standard CSV solution

As austincheney correctly points out, you really need to parse the string from start to finish if you wish to properly handle quoted strings that may contain escaped characters. Also, the OP does not clearly define what a "CSV string" really is. First we must define what constitutes a valid CSV string and its individual values.

正如austincheney正确指出的那样,如果你想正确处理可能包含转义字符的带引号的字符串,你真的需要从头到尾解析字符串。此外,OP没有明确定义“CSV字符串”究竟是什么。首先,我们必须定义什么构成有效的CSV字符串及其各个值。

Given: "CSV String" Definition

For the purpose of this discussion, a "CSV string" consists of zero or more values, where multiple values are separated by a comma. Each value may consist of:

出于本讨论的目的,“CSV字符串”由零个或多个值组成,其中多个值由逗号分隔。每个值可能包括:

  1. A double quoted string. (may contain unescaped single quotes.)
  2. 双引号字符串。 (可能包含未转义的单引号。)

  3. A single quoted string. (may contain unescaped double quotes.)
  4. 单引号字符串。 (可能包含未转义的双引号。)

  5. A non-quoted string. (may NOT contain quotes, commas or backslashes.)
  6. 未引用的字符串。 (不得包含引号,逗号或反斜杠。)

  7. An empty value. (An all whitespace value is considered empty.)
  8. 空值。 (所有空白值都被视为空。)

Rules/Notes:

  • Quoted values may contain commas.
  • 带引号的值可能包含逗号。

  • Quoted values may contain escaped-anything, e.g. 'that\'s cool'.
  • 引用的值可能包含转义任何内容,例如'这很酷'。

  • Values containing quotes, commas, or backslashes must be quoted.
  • 必须引用包含引号,逗号或反斜杠的值。

  • Values containing leading or trailing whitespace must be quoted.
  • 必须引用包含前导或尾随空格的值。

  • The backslash is removed from all: \' in single quoted values.
  • 在单引号值中从所有:\'中删除反斜杠。

  • The backslash is removed from all: \" in double quoted values.
  • 反斜杠从所有:\“中删除双引号值。

  • Non-quoted strings are trimmed of any leading and trailing spaces.
  • 任何前导和尾随空格都会修剪非引用字符串。

  • The comma separator may have adjacent whitespace (which is ignored).
  • 逗号分隔符可以具有相邻的空格(被忽略)。

Find:

A JavaScript function which converts a valid CSV string (as defined above) into an array of string values.

一种JavaScript函数,用于将有效的CSV字符串(如上所述)转换为字符串值数组。

Solution:

The regular expressions used by this solution are complex. And (IMHO) all non-trivial regexes should be presented in free-spacing mode with lots of comments and indentation. Unfortunately, JavaScript does not allow free-spacing mode. Thus, the regular expressions implemented by this solution are first presented in native regex syntax (expressed using Python's handy: r'''...''' raw-multi-line-string syntax).

此解决方案使用的正则表达式很复杂。而且(恕我直言)所有非平凡的正则表达式都应该以*间隔模式呈现,并带有大量的注释和缩进。不幸的是,JavaScript不允许*间隔模式。因此,此解决方案实现的正则表达式首先以本机正则表达式语法呈现(使用Python的方便表达:r''''''''raw-multi-line-string语法)。

First here is a regular expression which validates that a CVS string meets the above requirements:

首先是一个正则表达式,它验证CVS字符串是否满足上述要求:

Regex to validate a "CSV string":

re_valid = r"""# Validate a CSV string having single, double or un-quoted values.^                                   # Anchor to start of string.\s*                                 # Allow whitespace before value.(?:                                 # Group for value alternatives.  '[^'\\]*(?:\\[\S\s][^'\\]*)*'     # Either Single quoted string,| "[^"\\]*(?:\\[\S\s][^"\\]*)*"     # or Double quoted string,| [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*    # or Non-comma, non-quote stuff.)                                   # End group of value alternatives.\s*                                 # Allow whitespace after value.(?:                                 # Zero or more additional values  ,                                 # Values separated by a comma.  \s*                               # Allow whitespace before value.  (?:                               # Group for value alternatives.    '[^'\\]*(?:\\[\S\s][^'\\]*)*'   # Either Single quoted string,  | "[^"\\]*(?:\\[\S\s][^"\\]*)*"   # or Double quoted string,  | [^,'"\s\\]*(?:\s+[^,'"\s\\]+)*  # or Non-comma, non-quote stuff.  )                                 # End group of value alternatives.  \s*                               # Allow whitespace after value.)*                                  # Zero or more additional values$                                   # Anchor to end of string."""

If a string matches the above regex, then that string is a valid CSV string (according to the rules previously stated) and may be parsed using the following regex. The following regex is then used to match one value from the CSV string. It is applied repeatedly until no more matches are found (and all values have been parsed).

如果字符串与上述正则表达式匹配,则该字符串是有效的CSV字符串(根据前面所述的规则),并且可以使用以下正则表达式进行解析。然后使用以下正则表达式匹配CSV字符串中的一个值。重复应用它,直到找不到更多匹配项(并且已解析所有值)。

Regex to parse one value from valid CSV string:

re_value = r"""# Match one value in valid CSV string.(?!\s*$)                            # Don't match empty last value.\s*                                 # Strip whitespace before value.(?:                                 # Group for value alternatives.  '([^'\\]*(?:\\[\S\s][^'\\]*)*)'   # Either $1: Single quoted string,| "([^"\\]*(?:\\[\S\s][^"\\]*)*)"   # or $2: Double quoted string,| ([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)  # or $3: Non-comma, non-quote stuff.)                                   # End group of value alternatives.\s*                                 # Strip whitespace after value.(?:,|$)                             # Field ends on comma or EOS."""

Note that there is one special case value that this regex does not match - the very last value when that value is empty. This special "empty last value" case is tested for and handled by the js function which follows.

请注意,此正则表达式不匹配有一个特殊情况值 - 该值为空时的最后一个值。这个特殊的“空的最后值”情况由下面的js函数测试和处理。

JavaScript function to parse CSV string:

// Return array of string values, or NULL if CSV string not well formed.function CSVtoArray(text) {    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;    // Return NULL if input string is not well formed CSV string.    if (!re_valid.test(text)) return null;    var a = [];                     // Initialize array to receive values.    text.replace(re_value, // "Walk" the string using replace with callback.        function(m0, m1, m2, m3) {            // Remove backslash from \' in single quoted values.            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));            // Remove backslash from \" in double quoted values.            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));            else if (m3 !== undefined) a.push(m3);            return ''; // Return empty string.        });    // Handle special case of empty last value.    if (/,\s*$/.test(text)) a.push('');    return a;};

Example input and output:

In the following examples, curly braces are used to delimit the {result strings}. (This is to help visualize leading/trailing spaces and zero-length strings.)

在以下示例中,花括号用于分隔{result strings}。 (这有助于可视化前导/尾随空格和零长度字符串。)

// Test 1: Test string from original question.var test = "'string, duppi, du', 23, lala";var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {string, duppi, du}    a[1] = {23}    a[2] = {lala} */
// Test 2: Empty CSV string.var test = "";var a = CSVtoArray(test);/* Array hes 0 elements: */
// Test 3: CSV string with two empty values.var test = ",";var a = CSVtoArray(test);/* Array hes 2 elements:    a[0] = {}    a[1] = {} */
// Test 4: Double quoted CSV string having single quoted values.var test = "'one','two with escaped \' single quote', 'three, with, commas'";var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {one}    a[1] = {two with escaped ' single quote}    a[2] = {three, with, commas} */
// Test 5: Single quoted CSV string having double quoted values.var test = '"one","two with escaped \" double quote", "three, with, commas"';var a = CSVtoArray(test);/* Array hes 3 elements:    a[0] = {one}    a[1] = {two with escaped " double quote}    a[2] = {three, with, commas} */
// Test 6: CSV string with whitespace in and around empty and non-empty values.var test = "   one  ,  'two'  ,  , ' four' ,, 'six ', ' seven ' ,  ";var a = CSVtoArray(test);/* Array hes 8 elements:    a[0] = {one}    a[1] = {two}    a[2] = {}    a[3] = { four}    a[4] = {}    a[5] = {six }    a[6] = { seven }    a[7] = {} */

Additional notes:

This solution requires that the CSV string be "valid". For example, unquoted values may not contain backslashes or quotes, e.g. the following CSV string is NOT valid:

此解决方案要求CSV字符串为“有效”。例如,未加引号的值可能不包含反斜杠或引号,例如以下CSV字符串无效:

var invalid1 = "one, that's me!, escaped \, comma"

This is not really a limitation because any sub-string may be represented as either a single or double quoted value. Note also that this solution represents only one possible definition for: "Comma Separated Values".

这不是真正的限制,因为任何子字符串都可以表示为单引号或双引号。另请注意,此解决方案仅代表一种可能的定义:“逗号分隔值”。

Edit: 2014-05-19: Added disclaimer.Edit: 2014-12-01: Moved disclaimer to top.

编辑次数:2014-05-19:已添加免责声明。编辑:2014-12-01:将免责声明移至顶部。

#2


23  

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.

这不解决问题中的字符串,因为它的格式不符合RFC 4180;可接受的编码是双引号双引号。以下解决方案可正确使用谷歌电子表格中的CSV文件d / l。

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:

解析单行是错误的。根据RFC 4180字段可能包含CRLF,这将导致任何行读取器中断CSV文件。这是一个解析CSV字符串的更新版本:

'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));

OLD ANSWER

(Single line solution)

(单线解决方案)

function CSVtoArray(text) {    let ret = [''], i = 0, p = '', s = true;    for (let l in text) {        l = text[l];        if ('"' === l) {            s = !s;            if ('"' === p) {                ret[i] += '"';                l = '-';            } else if ('' === p)                l = '-';        } else if (s && ',' === l)            l = ret[++i] = '';        else            ret[i] += l;        p = l;    }    return ret;}let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,five for fun';console.log(CSVtoArray(test));

And for the fun, here is how you create CSV from the array:

为了好玩,以下是从阵列创建CSV的方法:

function arrayToCSV(row) {    for (let i in row) {        row[i] = row[i].replace(/"/g, '""');    }    return '"' + row.join('","') + '"';}let row = [  "one",  "two with escaped \" double quote",  "three, with, commas",  "four with no quotes (now has)",  "five for fun"];let text = arrayToCSV(row);console.log(text);

#3


6  

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

在http://en.wikipedia.org/wiki/Comma-separated_values处理RFC 4180示例的PEG(.js)语法:

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.

在http://jsfiddle.net/knvzk/10或https://pegjs.org/online进行测试。

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

通过https://gist.github.com/3362830下载生成的解析器。

#4


3  

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/

我喜欢FakeRainBrigand的答案,但是它包含一些问题:它不能处理引号和逗号之间的空格,并且不支持2个连续的逗号。我尝试编辑他的答案,但我的编辑遭到了显然不理解我的代码的审稿人的拒绝。这是我的FakeRainBrigand代码版本。还有一个小提琴: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('|'));

#5


2  

If you can have your quote delimiter be double-quotes, then this is a duplicate of JavaScript Code to Parse CSV Data.

如果您可以将引号分隔符设置为双引号,则这是JavaScript代码与解析CSV数据的副本。

You can either translate all single-quotes to double-quotes first:

您可以先将所有单引号翻译为双引号:

string = string.replace( /'/g, '"' );

...or you can edit the regex in that question to recognize single-quotes instead of double-quotes:

...或者您可以编辑该问题中的正则表达式以识别单引号而不是双引号:

// Quoted fields."(?:'([^']*(?:''[^']*)*)'|" +

However, this assumes certain markup that is not clear from your question. Please clarify what all the various possibilities of markup can be, per my comment on your question.

但是,这假定某些标记在您的问题中不明确。请根据我对您的问题的评论,澄清标记的各种可能性。

#6


2  

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.

我有一个非常具体的用例,我想将Google表格中的单元格复制到我的网络应用程序中。单元格可以包含双引号和换行符。使用复制和粘贴,单元格由制表符分隔,带有奇数数据的单元格是双引号。我尝试了这个主要的解决方案,链接的文章使用regexp,Jquery-CSV和CSVToArray。 http://papaparse.com/是唯一一个开箱即用的产品。使用默认的自动检测选项,Google表格可以无缝复制和粘贴。

#7


1  

My answer presumes your input is a reflection of code/content from web sources where single and double quote characters are fully interchangeable provided they occur as an non-escaped matching set.

我的回答假设您的输入是来自Web源代码/内容的反映,其中单引号和双引号字符完全可互换,前提是它们作为非转义匹配集出现。

You cannot use regex for this. You actually have to write a micro parser to analyze the string you wish to split. I will, for the sake of this answer, call the quoted parts of your strings as sub-strings. You need to specifically walk across the string. Consider the following case:

你不能使用正则表达式。实际上你必须编写一个微解析器来分析你想要分割的字符串。为了这个答案,我会将字符串的引用部分称为子字符串。你需要专门走过这个字符串。考虑以下情况:

var a = "some sample string with \"double quotes\" and 'single quotes' and some craziness like this: \\\" or \\'",    b = "sample of code from JavaScript with a regex containing a comma /\,/ that should probably be ignored.";

In this case you have absolutely no idea where a sub-string starts or ends by simply analyzing the input for a character pattern. Instead you have to write logic to make decisions on whether a quote character is used a quote character, is itself unquoted, and that the quote character is not following an escape.

在这种情况下,通过简单地分析字符模式的输入,您完全不知道子字符串的开始或结束位置。相反,您必须编写逻辑来决定引用字符是否使用引号字符,本身是否未引用,以及引号字符是否跟随转义。

I am not going to write that level of complexity of code for you, but you can look at something I recently wrote that has the pattern you need. This code has nothing to do with commas, but is otherwise a valid enough micro-parser for you to follow in writing your own code. Look into the asifix function of the following application:

我不打算为你编写那么复杂的代码,但你可以看看我最近编写的具有你需要的模式的东西。此代码与逗号无关,但在其他方面是一个有效的微解析器,您可以在编写自己的代码时遵循。查看以下应用程序的asifix函数:

https://github.com/austincheney/Pretty-Diff/blob/master/fulljsmin.js

#8


1  

People seemed to be against RegEx for this. Why?

人们似乎反对RegEx。为什么?

(\s*'[^']+'|\s*[^,]+)(?=,|$)

Here's the code. I also made a fiddle.

这是代码。我也做了一个小提琴。

String.prototype.splitCSV = function(sep) {  var regex = /(\s*'[^']+'|\s*[^,]+)(?=,|$)/g;  return matches = this.match(regex);    }var string = "'string, duppi, du', 23, 'string, duppi, du', lala";var parsed = string.splitCSV();alert(parsed.join('|'));

#9


1  

While reading csv to string it contain null value in between string so try it \0 Line by line it works me.

在读取csv到字符串时,它在字符串之间包含空值,所以试试它\ 0逐行它对我有用。

stringLine = stringLine.replace( /\0/g, "" );

#10


1  

To complement this answer

补充这个答案

If you need to parse quotes escaped with another quote, example:

如果您需要解析使用其他引号转义的引号,例如:

"some ""value"" that is on xlsx file",123

You can use

您可以使用

function parse(text) {  const csvExp = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|"([^""]*(?:"[\S\s][^""]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;  const values = [];  text.replace(csvExp, (m0, m1, m2, m3, m4) => {    if (m1 !== undefined) {      values.push(m1.replace(/\\'/g, "'"));    }    else if (m2 !== undefined) {      values.push(m2.replace(/\\"/g, '"'));    }    else if (m3 !== undefined) {      values.push(m3.replace(/""/g, '"'));    }    else if (m4 !== undefined) {      values.push(m4);    }    return '';  });  if (/,\s*$/.test(text)) {    values.push('');  }  return values;}

#11


1  

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 -

当我必须解析CSV文件时,我也遇到了同样的问题。文件包含一个包含','的列地址。在将该CSV解析为JSON后,我将密钥映射不匹配,同时将其转换为JSON文件。我使用node解析文件和库像baby parse和csvtojson文件示例 -

address,pincodefoo,baar , 123456

While I was parsing directly without using baby parse in JSON I was getting

虽然我直接解析而没有使用JSON中的婴儿解析,但我得到了

[{ address: 'foo', pincode: 'baar', 'field3': '123456'}]

So I wrote a code which removes the comma(,) with any other deliminatorwith every field

所以我写了一个代码,用每个字段删除逗号(,)与任何其他分隔符

/* csvString(input) = "address, pincode\\nfoo, bar, 123456\\n" output = "address, pincode\\nfoo {YOUR DELIMITER} bar, 123455\\n"*/const removeComma = function(csvString){    let delimiter = '|'    let Baby = require('babyparse')    let arrRow = Baby.parse(csvString).data;    /*      arrRow = [       [ 'address', 'pincode' ],      [ 'foo, bar', '123456']      ]    */    return arrRow.map((singleRow, index) => {        //the data will include         /*         singleRow = [ 'address', 'pincode' ]        */        return singleRow.map(singleField => {            //for removing the comma in the feild            return singleField.split(',').join(delimiter)        })    }).reduce((acc, value, key) => {        acc = acc +(Array.isArray(value) ?         value.reduce((acc1, val)=> {            acc1 = acc1+ val + ','            return acc1        }, '') : '') + '\n';        return acc;    },'')}

The function returned can be passed into csvtojson library and thus result can be used.

返回的函数可以传递给csvtojson库,因此可以使用结果。

const csv = require('csvtojson')let csvString = "address, pincode\\nfoo, bar, 123456\\n"let jsonArray = []modifiedCsvString = removeComma(csvString)csv()  .fromString(modifiedCsvString)  .on('json', json => jsonArray.push(json))  .on('end', () => {    /* do any thing with the json Array */  })
Now You can get the output like

[{  address: 'foo, bar',  pincode: 123456}]

#12


0  

According to this blog post, this function should do it:

根据这篇博文,这个函数应该这样做:

String.prototype.splitCSV = function(sep) {  for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {    if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {      if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {        foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");      } else if (x) {        foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));      } else foo = foo.shift().split(sep).concat(foo);    } else foo[x].replace(/''/g, "'");  } return foo;};

You would call it like so:

你会这样称呼它:

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

This jsfiddle kind of works, but it looks like some of the elements have spaces before them.

这种jsfiddle类型的工作,但看起来有些元素在它们之前有空格。

#13


0  

Aside from the excellent and complete answer from ridgerunner, I thought of a very simple workaround for when your backend runs php.

除了来自ridgerunner的优秀而完整的答案之外,我想到了一个非常简单的解决方法,当你的后端运行php时。

Add this php file to your domain's backend (say: csv.php)

将此php文件添加到域的后端(例如:csv.php)

<?phpsession_start(); //optionalheader("content-type: text/xml");header("charset=UTF-8");//set the delimiter and the End of Line character of your csv content:echo json_encode(array_map('str_getcsv',str_getcsv($_POST["csv"],"\n")));?>

Now add this function to your javascript toolkit (should be revised a bit to make crossbrowser I believe.)

现在将此函数添加到您的javascript工具包中(我应该稍微修改一下以制作crossbrowser。)

function csvToArray(csv) {    var oXhr = new XMLHttpRequest;    oXhr.addEventListener("readystatechange",            function () {                if (this.readyState == 4 && this.status == 200) {                    console.log(this.responseText);                    console.log(JSON.parse(this.responseText));                }            }    );    oXhr.open("POST","path/to/csv.php",true);    oXhr.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");    oXhr.send("csv=" + encodeURIComponent(csv));}

Will cost you 1 ajax call, but at least you won't duplicate code nor include any external library.

将花费你1 ajax调用,但至少你不会重复代码,也不包括任何外部库。

Ref: http://php.net/manual/en/function.str-getcsv.php

#14


0  

You can use papaparse.js like the example bellow:

您可以像下面的示例一样使用papaparse.js:

<!DOCTYPE html><html lang="en"><head>    <title>CSV</title></head><body>    <input type="file" id="files" multiple="">    <button onclick="csvGetter()">CSV Getter</button>    <h3>The Result will be in the Console.</h3><script src="papaparse.min.js"></script><script>     function csvGetter() {        var file = document.getElementById('files').files[0];        Papa.parse(file, {            complete: function(results) {                console.log(results.data);                }           });        }  </script>

Don't Forget to include papaparse.js in the same folder.

不要忘记将papaparse.js包含在同一个文件夹中。