match() method

The match() method in Apps Script is used to search a string for a specified pattern, and returns the matched substring as an array. It takes one argument: the regular expression pattern to be searched for in the string.

Example 1: Matching a Country Name
Suppose we want to check if a given string contains the name of a country, such as “Canada”. We can use the match() method with a regular expression pattern like so:

var str = "I love Canada!";
var pattern = /Canada/;
var match = str.match(pattern);
Logger.log(match);

In this example, we define a string str that contains the text we want to search. We define a regular expression pattern /Canada/ that matches the string “Canada”. We use the match() method on the string to search for the pattern, and assign the result to a new variable match. Finally, we log the value of match to the console using the Logger.log() method. If the string contains the pattern, the match variable will be an array containing the matched substring; if not, it will be null.

Example 2: Matching City Names
Suppose we have a list of city names in a Google Sheet, and we want to extract all the cities that contain the word “York”. We can use the match() method along with the forEach() method like so:

function findYorkCities() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cities = sheet.getRange("A1:A10").getValues().flat();
  var pattern = /York/;
  var yorkCities = [];
  cities.forEach(function(city) {
    var match = city.match(pattern);
    if (match) {
      yorkCities.push(city);
    }
  });
  Logger.log(yorkCities);
}

In this example, we use the getActiveSpreadsheet() and getActiveSheet() methods to get a reference to the current Google Sheet. We use the getRange() and getValues() methods to extract the city names from cells A1 to A10 on the sheet, and assign the result to an array cities. We define a regular expression pattern /York/ that matches the string “York”. We define an empty array yorkCities to hold the matching cities. We use the forEach() method on the cities array to iterate over each city name, and use the match() method to search for the pattern in each name. If a match is found, we push the city name to the yorkCities array. Finally, we log the value of yorkCities to the console using the Logger.log() method.

By using the match() method in Apps Script, we can easily search strings for patterns and extract the matching substrings. This can be useful for tasks such as data processing, text analysis, and more.