/ Published in: JavaScript
Extend string prototype to allow delimited text parsing, with knowledge of number of columns to expect. Usage: myString.parseDelim(",",2);
Expand |
Embed | Plain Text
String.prototype.parseDelim = function(delim,columns){ var qo = false; // qo = quotes open var rc = 0; // rc = row count var cc = 0; // cc = column count var i = 0; // i = seek index var bi = 0; // bi = beginning index var ln = this.length // ln = string length; var data = [] // data = data output var cp = this.replace(/ /g,"\n"); // copy = this string, with normalized newlines var v = "";// process value // re-usable fill function var fill = function(value){ v = value.replace(/^\s*|\s*$/g,"").replace(/""/g,'"'); if(v[0] == '"' && v[v.length-1] == '"'){ v = v.substring(1,v.length-1); } if(data.length < (rc+1)) data[data.length] = []; data[data.length-1][cc] = v; cc +=1; if(cc == columns){ rc += 1; cc = 0; } bi = bi+value.length; }; if(ln > 1){ while(i<ln){ // switch status of quotes open with each double quote if(cp[i] == '"'){ qo = !qo; // store value if a delimiter or newline is hit and quotes aren't open } else if(cp[i] == delim && qo === false){ fill(cp.substring(bi,i)); } else if(cp[i] == "\n" && qo === false){ fill(cp.substring(bi,i)); } i++; } // store final value fill(cp.substring(bi,i)); return data; } else { return [this]; } }
You need to login to post a comment.
