Google Script to see if text contains a value

前端 未结 4 1192
既然无缘
既然无缘 2021-02-06 22:25

I have a google form that when the user submits it will trigger my function to run which is creating a summary of what they submitted as a Google Doc. I know it can automaticall

相关标签:
4条回答
  • 2021-02-06 22:37

    Update 2020:

    You can now use Modern ECMAScript syntax thanks to V8 Runtime.

    You can use includes():

    var grade = itemResponse.getResponse();
    if(grade.includes("9th")){do something}
    
    0 讨论(0)
  • 2021-02-06 22:37

    I had to add a .toString to the item in the values array. Without it, it would only match if the entire cell body matched the searchTerm.

    function foo() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var s = ss.getSheetByName('spreadsheet-name');
        var r = s.getRange('A:A');
        var v = r.getValues();
        var searchTerm = 'needle';
        for(var i=v.length-1;i>=0;i--) {
            if(v[0,i].toString().indexOf(searchTerm) > -1) {
                // do something
            }
        }
    };
    
    0 讨论(0)
  • 2021-02-06 22:48

    Google Apps Script is javascript, you can use all the string methods...

    var grade = itemResponse.getResponse();
    if(grade.indexOf("9th")>-1){do something }
    

    You can find doc on many sites, this one for example.

    0 讨论(0)
  • 2021-02-06 22:49

    I used the Google Apps Script method indexOf() and its results were wrong. So I wrote the small function Myindexof(), instead of indexOf:

    function Myindexof(s,text)
    {
      var lengths = s.length;
      var lengtht = text.length;
      for (var i = 0;i < lengths - lengtht + 1;i++)
      {
        if (s.substring(i,lengtht + i) == text)
          return i;
      }
      return -1;
    }
    
    var s = 'Hello!';
    var text = 'llo';
    if (Myindexof(s,text) > -1)
       Logger.log('yes');
    else
       Logger.log('no');
    
    0 讨论(0)
提交回复
热议问题