1
votes

I'm struggling to figure out why the Javascript includes() function I'm using here isn't matching and returning true. The code is used in a Google Script on a Google Sheet to populate some cell values. Here's the relevant code from the full script:

const currentYear = getCurrentYear();

//Get current year from active sheet name
function getCurrentYear(){

  year = sheetName.slice(-7, -2);
  return year; //returns "2020"

}

//Return Current Control File ID
function getCurrentControlFileId(){
  
  const controlFolder = DriveApp.getFolderById(controlFolderId);
  const controlFiles = controlFolder.getFiles();
  
  while (controlFiles.hasNext()){
    let controlFile = controlFiles.next();
    let currentControlFileName = controlFile.getName(); // Evaluates to "CONTROL 2020"
    let searchString = `${currentYear}`; // Evaluates to "2020"
    //Have also tried:
    //let searchString = currentYear; 
    
    if (currentControlFileName.includes(searchString)){
      let controlFileId = controlFile.getId();
      return controlFileId;
    }
  }
  
}

controlFile.getName().includes(searchString) returns false even though controlFile.getName() value is "CONTROL 2020" and searchString value is "2020". Both are strings. If I manually enter "2020" into the if statement conditions like this:

controlFile.getName().includes("2020") it returns true and works as expected, returning the ID string. I've also tried wrapping currentYear and controlFile.getName() in String() but it still returns false. I really can't see what the problem is here, would appreciate some help.

1
Can't reproduce the situation your are describing. Can you test this: Logger.log(searchString==="2020") ? If that returns false, then there is an issue in searchString.soMario
@Marios Thanks for suggestions. In the Stackdriver logs it's coming back as false. Very odd since searchString returns what looks like "2020" but isn't interpreted that way. Any idea?Diagonali
Can you check then : Logger.log(typeof searchString) ? also try to see if the value is 2020 and not "2020" by Logger.log(searchString)soMario
@Marios The logger says typeof is String and the value itself is "2020" (without quotes).Diagonali
I've added: 'ui.alert(typeof currentControlFileName); ui.alert(currentControlFileName); Logger.log(typeof currentControlFileName); Logger.log(currentControlFileName);' and the logger shows they are both strings and the values are "2020" for searchString and "CONTROL 2020" for currentControlFileName.Diagonali

1 Answers

2
votes

Most likely year includes an empty space

You can doublecheck it with Logger.log(year.length);.

Beware that the when using array.slice(start, end) that the end index is the first element that it not included in your result. So, if you expect as output "2020" (corresponding to year.length=4):

end-start should equal to 4.

If your sheet name is something like "XXX 2020 YY" you should modify the definition of year to

year = sheetName.slice(-7, -3);