谷歌文档脚本,搜索和替换文本字符串和更改字体(例如,粗体)

Luk*_*e V 5 google-apps-script

我是google doc脚本的新手.

在谷歌文档中,我需要搜索几个文本字符串(例如,光照字体中的"学生1")以用另一个文本字符串(例如," 学生A ")替换这些文本字符串,但是用粗体字体.

要搜索和替换,我使用以下代码:

function docReplace() {

  var body = DocumentApp.getActiveDocument().getBody();
  // change "student 1" to "Student A" in boldface
  body.replaceText("student 1", "Student A");

}
Run Code Online (Sandbox Code Playgroud)

上面的代码只使用google doc的当前字体将"student 1"替换为"Student A",但我不知道如何将字体从lightface更改为粗体.

我试过了

body.replaceText("student 1", "<b>Student A</b>");
Run Code Online (Sandbox Code Playgroud)

当然,上面的代码没有用.

任何帮助将非常感激.谢谢.

Luk*_*e V 5

一种行人方式,用新的文本字符串替换在谷歌文档中出现多次的文本字符串(例如"学生1")(例如," 学生A"粗体字 ")在是两个步骤:

1-编写一个函数(称为docReplace),以常规/普通字体(无粗体)进行搜索和替换:

function docReplace() {

  var body = DocumentApp.getActiveDocument().getBody();
  // change "student 1" to "Student A"
  body.replaceText("student 1", "Student A");

}
Run Code Online (Sandbox Code Playgroud)

2-编写一个函数(称为boldfaceText),在每次出现时搜索所需的文本(例如"Student A")和该文本的两个偏移值(即startOffset和endOffsetInclusive)以设置字体对于这些偏移值中的字符为粗体:

function boldfaceText(findMe) {

  // put to boldface the argument
  var body = DocumentApp.getActiveDocument().getBody();
  var foundElement = body.findText(findMe);

  while (foundElement != null) {
    // Get the text object from the element
    var foundText = foundElement.getElement().asText();

    // Where in the Element is the found text?
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    // Change the background color to yellow
    foundText.setBold(start, end, true);

    // Find the next match
    foundElement = body.findText(findMe, foundElement);
  }

}
Run Code Online (Sandbox Code Playgroud)

上面的boldfaceText代码的灵感来自于发布文章中的内容(多次)和突出显示.

字符的偏移值只是描述文档中该字符位置的整数,第一个字符的偏移值为1(就像字符的坐标一样).

使用"Student A"作为调用函数boldfaceText的参数,即

boldfaceText("Student A");
Run Code Online (Sandbox Code Playgroud)

它可以嵌入到函数docReplace中,即

function docReplace() {

  var body = DocumentApp.getActiveDocument().getBody();
  // change "student 1" to "Student A"
  body.replaceText("student 1", "Student A");

  // set all occurrences of "Student A" to boldface
  boldfaceText("Student A");

}
Run Code Online (Sandbox Code Playgroud)

在谷歌文档中,只需运行脚本docReplace即可将所有出现的"学生1"更改为" 学生A ",并以粗体显示.

以上两个函数(docReplace和boldfaceText)可能是将新手(比如我)引入谷歌文档脚本的好方法.经过一段时间玩谷歌文档脚本以获得一些熟悉,学习罗宾更优雅和高级的代码,一次完成上述两个步骤.


Rob*_*ach 3

通过轻松查找和替换即可完成将一个字符串替换为另一个字符串的操作。

将它们设置为粗体有点困难,因为您必须获取正文的文本元素,并找到每个单词出现的开始和结束位置。

由于 JS 中的正则表达式不返回匹配数组,而是返回当前匹配的属性数组,因此您必须循环遍历该函数,该函数始终在最后一个匹配之后开始。

 function docReplace(input, output) {
  var re = new RegExp(output,"g");
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText(input, output);

  var text = body.getText();
  var index;
  while(true){
    index = re.exec(text)
    if(index == null){break}
    body.editAsText().setBold(index.index, output.length + index.index, true);
  }
}
Run Code Online (Sandbox Code Playgroud)