String starts with in Google Script

2020-08-11 11:14发布

问题:

I am working on a data converting script for some elections we are doing. The first part changes all the names to upper case, and this part of the script works fine. However, I have a problem with the second part of the script. Some IDs will have an S, S123456, and some will not have an S, 123456. For my purposes I need all IDs to have no s at the beginning. When I run this script in Google it returns

TypeError: Cannot find function startsWith in object S123456.

Any ideas?

function convertResponseData(){
  var resultsInformation = SpreadsheetApp.openById('MySheetID').getSheetByName('Election Responses');
  var resultsDataRange = resultsInformation.getRange(1, 1, 2500, 6);
  var resultsData = resultsDataRange.getValues();
  for (var i = 0; i < resultsData.length; i++) {
    var row = resultsData[i];
    var resultsStudentNameLower = row[1];
    var resultsStudentID = row[2]
    var studentNameUpper = resultsStudentNameLower.toUpperCase()
    resultsInformation.getRange(i+1, 2).setValue(studentNameUpper)
    if (var n = resultsStudentID.startsWith("S")){
      var resultsStudentIDNoS = resultsStudentID.substring(1,20);
      resultsInformation.getRange(i+1, 3).setValue(resultsStudentIDNoS)
    }
  }
}

回答1:

startsWith() is not supported in google scripts. Instead, you can use

resultsStudentID.indexOf("S") == 0 

To check if the string start starts with "S"

function convertResponseData(){
  var resultsInformation = SpreadsheetApp.openById('MySheetID').getSheetByName('Election Responses');
  var resultsDataRange = resultsInformation.getRange(1, 1, 2500, 6);
  var resultsData = resultsDataRange.getValues();
  for (var i = 0; i < resultsData.length; i++) {
    var row = resultsData[i];
    var resultsStudentNameLower = row[1];
    var resultsStudentID = row[2]
    var studentNameUpper = resultsStudentNameLower.toUpperCase()
    resultsInformation.getRange(i+1, 2).setValue(studentNameUpper)
    if (resultsStudentID.indexOf("S") == 0 ){
      var resultsStudentIDNoS = resultsStudentID.substring(1,20);  //You also do this resultsStudentID.substring(1) to get a substring from index 1 to end. 
      resultsInformation.getRange(i+1, 3).setValue(resultsStudentIDNoS)
    }
  }
}

Hope that helps