ChaPPer5
ChaPPer5

Reputation: 105

Google Sheets script: how do I run a script only on the sheets whose names contain particular text?

(On Google Sheets) I want to create a script that runs only on certain sheets in a spreadsheet. To do this I have created a script that creates an array of sheet names whose names (defined as a variable curSheetName) fit the following condition:

if(curSheetName == "CM:")

so currently the sheet name must equal "CM:", however I want it to be so that the script runs on all sheets that CONTAIN the text "CM:" in their title, but I can't find how to write that syntactically. In MySQL it is '%CM:%', in GSheet formulas you just use asterisks..

Here is my code:

// Get list of sheet names in an array format
function sheetnames() {
  // Define array
  var out = new Array()
  // Get sheets
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  // Work through each sheet one at a time
  for (var i=0 ; i<sheets.length ; i++) {
    // define the current sheet
    var curSheetName = sheets[i].getName();
    // determine if matches criteria
    if(curSheetName == "CM:") { //***************** NEED HELP HERE
      // put into array if matches criteria
      out.push( [ sheets[i].getName() ] );
//      RUN FUNCTION HERE
    }
  }
}

Any help appreciated! Cheers, Mike

Upvotes: 0

Views: 861

Answers (1)

ross
ross

Reputation: 2774

You can use the JavaScript Array.indexOf() method to achieve this.


Example:

if (curSheetName.indexOf('CM:') !== -1) {
  ...
}

Documentation:

Upvotes: 3

Related Questions