By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
462,168 Members | 584 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 462,168 IT Pros & Developers. It's quick & easy.

CSV to Javascript arrays

P: 25
Hi,

I have a requirement to convert CSV values entered by user into a Javascript array (of arrays).

No server roundtrip should be made and it should be totally offline/client-side.

If possible, the script should be browser independent.

I have seen a previous post http://www.thescripts.com/forum/thread146456.html but could not find any code level hints.

I know I could use split function and write my own parsing code. But if it is a single line I know the logic can be something like the below, but what if there is a multi-line CSV data in a TextArea?

Expand|Select|Wrap|Line Numbers
  1. function jsSplitString(stringToSplit){
  2.  
  3. var splitArray = stringToSplit.split(",");
  4.  
  5. for (var i = 0; i < splitArray.length; i++){
  6. // add to array 
  7. }
  8.  
  9. }
  10.  
-Ramesh.
Oct 22 '07 #1
Share this Question
Share on Google+
3 Replies

gits
Expert Mod 5K+
P: 5,390
hi ...

welcome to TSDN ...

in case you have a multiline text you may use something like the following example, t is a multiline text:

Expand|Select|Wrap|Line Numbers
  1. // multiline text
  2. var t = 'abcx,hjhk,hjsahk,klö\nabcx,hjhk,hjsahk,klö\n';
  3.  
  4. // we alert it to have a look :)
  5. alert(t);
  6.  
  7. // we split it first at the linebreaks
  8. var ts = t.split(/\n|\n\r/);
  9.  
  10. // alert first line
  11. alert(ts[0]);
  12.  
now you may combine this with your code ... and you should be on track :)

kind regards
Oct 22 '07 #2

100+
P: 428
Expand|Select|Wrap|Line Numbers
  1. function csvArray(csv){
  2.     var i= 0, A= csv.split(/\s*\n\s*/);
  3.     while(A[i++]) A[i]= A[i].split(/ *, */);
  4.     return A;
  5. }
Every item in A will be an array of that line's data.
It will work for one line or any number of lines-
you don't often need a one line csv file.
In html terms, each A[index] array could be a row of cells.
Oct 22 '07 #3

gits
Expert Mod 5K+
P: 5,390
Expand|Select|Wrap|Line Numbers
  1. function csvArray(csv){
  2.     var i= 0, A= csv.split(/\s*\n\s*/);
  3.     while(A[i++]) A[i]= A[i].split(/ *, */);
  4.     return A;
  5. }
Every item in A will be an array of that line's data.
It will work for one line or any number of lines-
you don't often need a one line csv file.
In html terms, each A[index] array could be a row of cells.
note: this will trim all leading and ending spaces of a line due to the use of \s* ...

kind regards
Oct 23 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.