CSV to Javascript arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rameshch45
    New Member
    • Oct 2007
    • 25

    CSV to Javascript arrays

    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?

    [CODE=javascript]function jsSplitString(s tringToSplit){

    var splitArray = stringToSplit.s plit(",");

    for (var i = 0; i < splitArray.leng th; i++){
    // add to array
    }

    }
    [/CODE]
    -Ramesh.
    Last edited by gits; Oct 22 '07, 01:23 PM. Reason: added code tags
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi ...

    welcome to TSDN ...

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

    [CODE=javascript]
    // multiline text
    var t = 'abcx,hjhk,hjsa hk,klö\nabcx,hj hk,hjsahk,klö\n ';

    // we alert it to have a look :)
    alert(t);

    // we split it first at the linebreaks
    var ts = t.split(/\n|\n\r/);

    // alert first line
    alert(ts[0]);
    [/CODE]
    now you may combine this with your code ... and you should be on track :)

    kind regards

    Comment

    • mrhoo
      Contributor
      • Jun 2006
      • 428

      #3
      [CODE=javascript]function csvArray(csv){
      var i= 0, A= csv.split(/\s*\n\s*/);
      while(A[i++]) A[i]= A[i].split(/ *, */);
      return A;
      }[/CODE]

      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.

      Comment

      • gits
        Recognized Expert Moderator Expert
        • May 2007
        • 5390

        #4
        Originally posted by mrhoo
        [CODE=javascript]function csvArray(csv){
        var i= 0, A= csv.split(/\s*\n\s*/);
        while(A[i++]) A[i]= A[i].split(/ *, */);
        return A;
        }[/CODE]

        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

        Comment

        Working...