How to compare strings in google apps script

前端 未结 4 1542
盖世英雄少女心
盖世英雄少女心 2021-01-13 03:22

I am trying to compare string values that I have obtained from my google spreadsheet.

My Months appear in this format \" Jun13\", \"Aug13\" etc. and my script has tr

相关标签:
4条回答
  • 2021-01-13 03:54

    Just use '==' operator:

    if(myString != ''){
    //do something
    }
    

    Enjoy!

    0 讨论(0)
  • 2021-01-13 03:56

    try that:

    function test(){
      var ss = SpreadsheetApp.getActive().getSheetByName("month test");
      var data = ss.getRange(2,2,ss.getLastRow(),3).getValues();
      var ListOfMonths = new Array();  
      for(var i in data){
        var row = data[i][0].toString();
        if(ListOfMonths.indexOf(row)==-1){
          Logger.log(row+" is not referenced. Adding it");
          ListOfMonths.push(row);
        }
      }
      Logger.log(ListOfMonths);
    }
    
    0 讨论(0)
  • 2021-01-13 04:02

    Harold's code is more efficient than yours but it has a different logic... if you're interrested to know why your code didn't work here is a version that takes the same approach as yours but with a few bug corrections that make it work.

    Shortly described, you pushed the value at a wrong place in the loop and you forgot to add a first item to have at least one element in your second array. You didn't use match the right way, match returns the 'common' part in the string, not a boolean.

    Here is the code :

    function myFunction() {
      var ss = SpreadsheetApp.getActiveSheet();
      var data = ss.getRange(2,2,ss.getLastRow(),3).getValues();
      var ListOfMonths = new Array();
      ListOfMonths.push(data[0])
    
      for(var i = 0; i < data.length; ++i){
    
        var row = data[i];
        var duplicate = false;
    
        for(j in ListOfMonths){
          var item = ListOfMonths[j][0];
          if(row.toString().match(item) == item){
            duplicate = true;
            break;
          }
        }
        if(!duplicate && i<data.length-1){
          ListOfMonths.push(row); 
        }
      }
      Logger.log(ListOfMonths);
    }
    
    0 讨论(0)
  • 2021-01-13 04:20

    Is there any reason you can't use the '==' operator?

    if ( "April" == ListOfMonths[j][0] ) {
        Logger.log("Match!");
    }
    
    0 讨论(0)
提交回复
热议问题