繁体   English   中英

使用谷歌应用脚本格式化谷歌文档中的关键字

[英]Format keywords in google docs with google apps script

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

你好

你好

有效期

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的所有行都加粗?

您需要使用 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);
  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM