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

前端 未结 17 916
不知归路
不知归路 2020-11-22 01:52

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

17条回答
  •  死守一世寂寞
    2020-11-22 02:06

    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;
    }
    

提交回复
热议问题