从CSV JavaScript切片字符串

时间:2017-12-20 17:36:08

标签: javascript string csv

您好我在JavaScript中解析CSV文件有问题。结构CSV

<code> 
date, hours, text
2004-05-04,05:22, Sample text, with coma
2005-05-04,05:22:00, Another Sample text, with coma
2006-05-04,05:22, Third Sample text, with coma
</code>

要解析此CSV,请使用以下代码

<code>
$.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "text",
        success: function(data) {processData(data);}
     });
function processData(csv) {
    var allTextLines = csv.split(/\r\n|\n/);
    //console.log(allTextLines);
    var lines = [];
    while (allTextLines.length) {
        //console.log(allTextLines);
        lines.push(allTextLines.shift().split(","));
    }
    console.log(lines);
}
</code>

问题是,当我在文本中有逗号时,我有像这样的数组

<code>
lines[0]=['2004-05-04']['05:22'][Sample text][with comma];
</code>

我的问题是,如何将此转换为数组,如下所示:

<code>
lines[0]=['2004-05-04']['05:22'][Sample text, with coma];
</code>

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

以下递归函数会有所帮助,但取决于确切知道每行必须提取的列数。

&#13;
&#13;
/* $.ajax({
            type: "GET",
            url: "data.csv",
            dataType: "text",
            success: function(data) {processData(data);}
         });*/
         
    var csvtext = "date, hours, text\n2004-05-04,05:22, Sample text, with coma\n2005-05-04,05:22:00, Another Sample text, with coma\n2006-05-04,05:22, Third Sample text, with coma";
    
    processData(csvtext);
    
    function processData(csv) {
        var allTextLines = csv.split(/\r\n|\n/);
        
        var lines = [];
        while (allTextLines.length) {
            var lineSplit = [];
            pushStrings(0, allTextLines.shift(), 0, lineSplit);
            lines.push(lineSplit);
        }
        console.log(lines);
    }

    function pushStrings(start, string, count, arr){
        if(count == 2){
            arr.push(string);
            return false;
        }    
        startIndex = string.indexOf(',');
        var el = string.substring(start, startIndex)
        stringNew = string.substring(++startIndex);
        arr.push(el);
        pushStrings(0, stringNew.trim(), ++count, arr);
    }
    console.log(lines);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用正则表达式的示例。如果不匹配,您可能最想检查数组长度并执行一些错误处理。依赖于CSV是唯一的三列,最后一列是唯一包含其他逗号的列。如果可能的话,一种更干净的方式可能是从源头上删除你的逗号。

&#13;
&#13;
var csvtext = "date, hours, text\n2004-05-04,05:22, Sample text, with coma\n2005-05-04,05:22:00, Another Sample text, with coma\n2006-05-04,05:22, Third Sample text, with coma";

function processData(csv) {
  var allTextLines = csv.split(/\r\n|\n/);
  var lines = [];
  while (allTextLines.length) {
    var lineSplit = allTextLines.shift().match(/([^\,]+),\s?([^\,]+),\s?(.+)/i).splice(1);
    console.log(lineSplit);
    lines.push(lineSplit);
  }
  console.log(lines);
}

processData(csvtext);
&#13;
&#13;
&#13;