google-apps-scriptgoogle-sheets

How to GetSheetByName using partial string in google apps script


I am trying to use .getSheetByName('') to grab a sheet whose name contain a certain string like, 'V1' or 'V4', not an exact match. Say the name of the sheet is '2020 0304 V1', the first part is always changing but it contains V1, I tried .getSheetByName('*V1') but it is not working. Any hint on how to achieve this?


Solution

  • Issue and workaround:

    Unfortunately, in the current stage, the method like the regex cannot be used with getSheetByName(). So in this case, it is required to use the workarounds.

    In this answer, I would like to propose 2 patterns.

    Pattern 1:

    In this pattern, test is used for searching the sheet name. getSheetName() is used for retrieving the sheet name. In this case, it supposes that the pattern is like 2020 0304 V1.

    Sample script:

    function myFunction() {
      const searchText = "V1";
      
      const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
      const regex = RegExp(`\\d{4} \\d{4} ${searchText}`);
      const sheet = sheets.filter(s => regex.test(s.getSheetName()));
      if (sheet.length > 0) console.log(sheet[0].getSheetName());
    }
    

    Pattern 2:

    In this pattern, includes is used for searching the sheet name. getSheetName() is used for retrieving the sheet name.

    Sample script:

    function myFunction() {
      const searchText = "V1";
    
      const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
      const sheet = sheets.filter(s => s.getSheetName().includes(searchText));
      if (sheet.length > 0) console.log(sheet[0].getSheetName());
    }
    

    Note:

    References: