Ilya Kern
Ilya Kern

Reputation: 99

How to remove quote mark from array

I have a script that will import data from a csv file in to a Google sheet. I would like to include the following to remove the quote marks from the data - .replace(/"/g, "") - but am not sure of the best place/syntax to add in to the existing script.

Do I add it in to the section where I convert the csv data to an array -

    function CSVToArray_(strData){
      var rows = strData.split("\n");
      //Logger.log(rows.length);
      var array = [];
       for(n=0;n<rows.length;++n){
        if(rows[n].split(',').length>1){ 
        array.push(rows[n].split(','));
        }
        }
    Logger.log(array);
    return array;

}

...or to the section where the sheet gets updated with the array data ?

 var impSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B8:B8").getValue();
  var csvData = CSVToArray_(csvFile);// convert to 2D array
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName(impSheet);
      sheet.clear();
      sheet.getRange(1,1, csvData.length, csvData[0].length).setValues(csvData);// write to sheet in one single step 

Any guidance/suggestions would be greatly appreciated.

Upvotes: 1

Views: 2435

Answers (1)

mwakerman
mwakerman

Reputation: 138

The code above is dangerous and will break if there is a comma within an element even if it is in quotes which is valid csv. I suggest checking out this library https://code.google.com/p/jquery-csv/. Also, are you wanting to remove quotes or are you wanting to convert string values to numbers? That is, are you getting "2" and wanting it to be just 2, if so, you may just be wanting to parse it into a number as follows: parseInt("2").

If you don't care about the above then the following should work:

function CSVToArray_(strData){
    var rows = strData.split("\n");
    //Logger.log(rows.length);
    var array = [];
    var array_inner;
    // iterate over rows
    for (n=0; n<rows.length; ++n) {
        array_inner = rows[n].split(',');
        if (array_inner.length>1) {    
            // iterate over columns
            for (m=0; m<array_inner.length; m++) {
                array_inner[m] = array_inner[m].replace(/"/g, ""); 
            }
            array.push(array_inner);
        }
    }
    Logger.log(array);
    return array

}

Upvotes: 2

Related Questions