首页 > 解决方案 > 使用谷歌应用脚​​本格式化谷歌文档中的关键字

问题描述

我正在尝试为谷歌文档制作一个谷歌应用脚​​本,它将所有出现的字符串以粗体样式放在文档中,例如,对于这个文本:

你好

你好

有效期

000000000000000000 你好 00000

你好你好你好

000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好

如果字符串是hello,我希望脚本这样写:

你好

你好

有效期

000000000000000000你好00000

你好你好 你好

000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好

我做了这个代码:

  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  var Style = {};
  Style[DocumentApp.Attribute.BOLD] = true;

  var found = body.findText("hola");

  while(found != null) {
    found.getElement().setAttributes(Style);
    found = body.findText("hello", found);
  }

但是我在运行代码后得到的是:

你好

你好

有效期

000000000000000000 你好 00000

你好你好你好

000000000000000000111111111111111111111111122222222222222222222223333333333333333344444444444444444444444555555555555你好

所以代码将包含字符串的所有行都加粗hello,而不仅仅是字符串hello

有人知道我该怎么做才能只将字符串hello而不是包含的所有行加粗hello

标签: javascriptgoogle-apps-script

解决方案


您需要使用 getStartOffset() 和 getEndOffsetInclusive() 指定尝试编辑的文本的开始和结束。这将阻止您的脚本将整个文本块格式化为粗体。请看下面的代码:

function myFunction() {
  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  var Style = {};
  Style[DocumentApp.Attribute.BOLD] = true;

  var found = body.findText("hello");

  while(found != null) {
    var foundText = found.getElement().asText();
    var start = found.getStartOffset();
    var end = found.getEndOffsetInclusive();
    foundText.setAttributes(start, end, Style)
    found = body.findText("hello", found);
  }
}

运行这个结果是: 在此处输入图像描述


推荐阅读