Google Calendar – How to Delete Events with Specific Words in Title

google-apps-scriptgoogle-calendar

I'm trying to delete specific events on my Google calendar, I've found this script that delete events with a specific title:

function delete_events()
{
  //take care: Date function starts at 0 for the month (January=0)
  var fromDate = new Date(2014,7,1,0,0,0); //This is August 1, 2014
  var toDate = new Date(2016,2,1,0,0,0);   //This is March 1, 2016 at 00h00'00"
  var calendarName = 'your_calendar_name';
  var toRemove = 'title_of_the_events';

  var calendar = CalendarApp.getCalendarsByName(calendarName)[0];
  var events = calendar.getEvents(fromDate, toDate,{search: toRemove});
  for(var i=0; i<events.length;i++)
  {
    var ev = events[i];
    if(ev.getTitle()==toRemove) //check if the title matches
    {
      Logger.log('Item '+ev.getTitle()+' found on '+ev.getStartTime()); // show event name and date in log
      //ev.deleteEvent(); //uncomment this line to actually do the delete !
    }
  }
}

The events that I'm trying to delete have the same word in the begining of the title but the rest is different, example:

Sunrise: 6:26am, Sunset: 6:58pm

Sunrise: 6:22am, Sunset: 7:00pm

Sunrise: 6:20am, Sunset: 7:02pm

What I need to change in the code for the script delete all events with "Sunrise" in the title?

Best Answer

Only one line needs a change. Instead of the exact match

if (ev.getTitle() == toRemove)

you want to check that ev.getTitle() begins with the string toRemove. This is how:

if (ev.getTitle().slice(0, toRemove.length) == toRemove)

The slice command cuts down the event title to the same length as toRemove string. So, if toRemove is "Sunrise" and the title is "Sunrise: 6:20am, Sunset: 7:02pm", then

  • toRemove.length is 7, the length of the string Sunrise
  • the slice with parameters 0 and 7 is the first 7 characters of event title, which is Sunrise
  • the result matches toRemove, so the event gets removed