user2450833
user2450833

Reputation: 69

how to count number of values for each row in *.CSV file using javascript?

My csv Data looking like this

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

Upvotes: 1

Views: 2695

Answers (2)

mesterak
mesterak

Reputation: 41

Try this method which is derived from another post here:

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

Upvotes: 0

YOU
YOU

Reputation: 123881

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

Upvotes: 1

Related Questions