一行人的方式來替換文本字符串(例如,「學生1」),通過一個新的文本字符串有一個谷歌文檔許多事件(例如,「學生A」)粗體,是兩個步驟:
1-寫的函數(稱爲,比方說,docReplace)執行搜索和在常規/正常字體替換(無粗體):
function docReplace() {
var body = DocumentApp.getActiveDocument().getBody();
// change "student 1" to "Student A"
body.replaceText("student 1", "Student A");
}
2-寫的函數(稱爲,說,boldfaceText)來搜索所需的文本(例如「學生A」)和兩個偏差值用於該文本(即,開始偏移和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);
}
}
爲boldfaceText上述代碼被從在後Finding text (multiple times) and highlighting啓發。
字符的偏移量值只是描述該字符在文檔中的位置的整數,第一個字符的偏移值爲1(它就像字符的座標)。
使用「學生A」作爲參數用於向功能boldfaceText一個呼叫,即,
boldfaceText("Student A");
其可嵌入到功能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");
}
在谷歌文檔
,只需運行該腳本docReplace改變「學生1」所有出現到「學生A」黑體。
上述兩個函數(docReplace和boldfaceText)可能是將新手(如我)引入Google文檔腳本的好方法。經過一段時間玩谷歌文檔腳本,以獲得一些熟悉,學習羅賓的更優雅和先進的代碼,一次完成上述兩個步驟。
謝謝,羅賓。追加.setBold(true)的問題是整個文檔被設置爲粗體,而不是**我想要的。我只想將替換文本「** Student A **」設置爲粗體,而文檔中的其餘部分保持原樣。 –
請檢查更新後的函數,它將輸入轉換爲輸出並使其全部出現爲粗體。 –
謝謝,羅賓。你的新代碼更加優雅和先進,而且我正在迷失如何使用它。我沒有看到代碼中的任何地方,我可以用粗體文本「** Student A **」替換文本「student 1」。也許,我應該將輸入設置爲「學生1」並輸出爲「學生A」。是的,沒錯,我明白了。你的代碼確實有效。 –