当标题长于 1 个字符时,如何在 google 日历中有条件地格式化?

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

如有任何不明之处,我深表歉意,我对编码非常陌生。

我发现 Rick Pastoor (https://rickpastoor.com/2019/05/30/google-calendar-color-coder.html) 的这段代码可以根据事件开头的字符自动为我的 Google 日历中的事件添加颜色代码(在本例中为 ![#)。代码用于 Google Apps 脚本

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);
      }
    }
  }
}

现在,如果事件以单词 say:

开头,我希望它用颜色代码代替以 ! 开头的事件
if (title[0] == "Vacation") {
      e.setColor(CalendarApp.EventColor.RED);

但这不起作用。任何只有一个字符(字母、数字、符号)的东西都可以工作,但超过 1 个字符就不起作用,我想知道如何解决这个问题。提前致谢!

你的情况,下面的修改怎么样?

发件人:

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

收件人:

if ((/^Vacation/).test(title)) {
  • 比如要忽略大小写,可以使用if ((/^Vacation/i).test(title)) {.

参考:

title[0] returns 事件标题的第一个字符,但是您要匹配的不仅仅是第一个字符。

要匹配所有包含单词“假期”的活动标题,您可以这样做:

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

要匹配所有 完全等于 与单词“假期”的事件标题,您可以这样做:

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

要仅匹配单词“假期”开头的活动标题,您可以这样做:

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

请注意,以上所有内容都是 case-sensitive,这意味着名为“假期”的事件不会被着色。我建议在比较之前将搜索词和标题都小写。例如:

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