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.
Logger.log(searchString==="2020")
? If that returns false, then there is an issue insearchString
. – soMarioLogger.log(typeof searchString)
? also try to see if the value is 2020 and not "2020" byLogger.log(searchString)
– soMario