Home > other >  How to conditionally format in google calendar when title is longer than 1 character?
How to conditionally format in google calendar when title is longer than 1 character?

Time:01-14

Apologies in advance for any unclarities, I am extremely new to coding.

I found this code by Rick Pastoor (https://rickpastoor.com/2019/05/30/google-calendar-color-coder.html) to automatically colour code events in my Google Calendar based on what character the events start with (in this case !, [ and #).The code is for Google Apps Script

function ColorEvents() {
  var today = new Date();
  var nextweek = new Date();
  nextweek.setDate(nextweek.getDate()   7);
  Logger.log(today   " "   nextweek);
  var calendars = CalendarApp.getAllOwnedCalendars();
  Logger.log("found number of calendars: "   calendars.length);
  for (var i = 0; i < calendars.length; i  ) {
    var calendar = calendars[i];
    var events = calendar.getEvents(today, nextweek);
    for (var j = 0; j < events.length; j  ) {
      var e = events[j];
      var title = e.getTitle();
      if (title[0] == "[") {
        e.setColor(CalendarApp.EventColor.CYAN);
      }
      if (title[0] == "!") {
        e.setColor(CalendarApp.EventColor.RED);
      }
      if (title[0] == '#') {
        e.setColor(CalendarApp.EventColor.GREEN);
      }
    }
  }
}

Now instead of an event starting with !, I want it to colour code if an event starts with a word say:

if (title[0] == "Vacation") {
      e.setColor(CalendarApp.EventColor.RED);

This however doesn't work. Anything with just one character (letters, numbers, signs) work, but more than 1 character doesn't work and I was wondering how I could solve this. Thank you in advance!

CodePudding user response:

title[0] returns the first character of the event title, however you are looking to match more than the first character.

To match all event titles that contain the word "Vacation" you could do:

if (title.includes("Vacation")) {
  e.setColor(CalendarApp.EventColor.RED);
}

To match all events titles that are exactly equal to the word "Vacation" you could do:

if (title === "Vacation") {
  e.setColor(CalendarApp.EventColor.RED);
}

To match only event titles that begin with the word "Vacation" you could do:

const searchWord = "Vacation"
if (title.slice(0, searchWord.length) === searchWord) {
  e.setColor(CalendarApp.EventColor.RED);
}

Note that all the above are case-sensitive meaning an event named "vacation days" would not be colored. I would recommend instead lowercasing both your search word and the title before comparison. For example:

if (title.toLowerCase().includes("vacation")) {
  e.setColor(CalendarApp.EventColor.RED);
}

CodePudding user response:

In your situation, how about the following modification?

From:

if (title[0] == "!") {

To:

if ((/^Vacation/).test(title)) {
  • For example, if you want to ignore the uppercase and lowercase, you can use if ((/^Vacation/i).test(title)) {.

Reference:

  •  Tags:  
  • Related