如何使用javascript计算* .CSV文件中每行的值数?

时间:2013-08-02 04:57:19

标签: javascript csv row

我的csv数据看起来像这样

1,2,"hi,how ar you?",abc
3,5,a,b,c
expected output should be
4
5

2 个答案:

答案 0 :(得分:1)

'1,2,"hi,how ar you?",abc'.match(/"[^"]*"|[^,]+/g).length
4
'3,5,a,b,c'.match(/"[^"]*"|[^,]+/g).length
5

答案 1 :(得分:0)

尝试此方法,该方法来自另一篇文章:

   var csvLines = '1,2,"how ar you?",abc' + "\n" + '1,4,"fine",6,7';
   var splitByChars = ',';

   var totalCount = 0;
   var linesArray = csvLines.split("\n");

   var lineCount = 0;

   while (lineCount < linesArray.length) {
       totalCount += StringCount(csvLines, splitByChars);
       lineCount++;
   }

   alert(totalCount);

   function StringCount(stringToSplit, splitBy) {
       var words = stringToSplit.split(splitBy);
       return words.length;
   }