Posted By

mfoley on 05/18/09


Tagged

csv


Versions (?)

CSV Parse


 / Published in: JavaScript
 

Extend string prototype to allow delimited text parsing, with knowledge of number of columns to expect. Usage: myString.parseDelim(",",2);

  1. String.prototype.parseDelim = function(delim,columns){
  2. var qo = false; // qo = quotes open
  3. var rc = 0; // rc = row count
  4. var cc = 0; // cc = column count
  5. var i = 0; // i = seek index
  6. var bi = 0; // bi = beginning index
  7. var ln = this.length // ln = string length;
  8. var data = [] // data = data output
  9. var cp = this.replace(/
  10. /g,"\n"); // copy = this string, with normalized newlines
  11. var v = "";// process value
  12. // re-usable fill function
  13. var fill = function(value){
  14. v = value.replace(/^\s*|\s*$/g,"").replace(/""/g,'"');
  15. if(v[0] == '"' && v[v.length-1] == '"'){
  16. v = v.substring(1,v.length-1);
  17. }
  18. if(data.length < (rc+1)) data[data.length] = [];
  19. data[data.length-1][cc] = v;
  20. cc +=1;
  21. if(cc == columns){
  22. rc += 1;
  23. cc = 0;
  24. }
  25. bi = bi+value.length;
  26. };
  27. if(ln > 1){
  28. while(i<ln){
  29. // switch status of quotes open with each double quote
  30. if(cp[i] == '"'){
  31. qo = !qo;
  32. // store value if a delimiter or newline is hit and quotes aren't open
  33. } else if(cp[i] == delim && qo === false){
  34. fill(cp.substring(bi,i));
  35. } else if(cp[i] == "\n" && qo === false){
  36. fill(cp.substring(bi,i));
  37. }
  38. i++;
  39. }
  40. // store final value
  41. fill(cp.substring(bi,i));
  42. return data;
  43. } else {
  44. return [this];
  45. }
  46. }

Report this snippet  

You need to login to post a comment.