[英]Paint certain words in google docs - Google Apps Script
I have this code below:我在下面有这段代码:
var textToHighlight = 'Normal';
var highLightStyle = {};
highLightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FFC0CB';
var paras = doc.getParagraphs();
var textLocation = {};
for (i=0; i<paras.lenght; i++) {
textLocation = paras[i].findText(textToHighlight);
if (textLocation != null && textLocation.getStartOffset() != -1) {
textLocation.getElement().setAttributes(textLocation.getStartOffset(), textLocation.getEndOffsetInclusive(), highLightStyle);
}
}
With it, I want to color all the words 'normal' that appear in my document, but when I run the code, nothing happens and it doesn't accuse any error, it compiles normally.有了它,我想为我的文档中出现的所有单词“正常”着色,但是当我运行代码时,没有任何反应,也没有指责任何错误,它可以正常编译。
I tried this another code:我尝试了另一个代码:
let pinkColor = "#FFC0CB"
let pinkElements = body.findText("Normal")
let elem = pinkElements.getElement().asText();
let t = elem.getText();
elem.setForegroundColor(t.indexOf('Normal'), t.indexOf('High')+3, pinkColor)
But with the code above it paints only the first word 'Normal' that it finds, the rest remains neutral.但是上面的代码只绘制了它找到的第一个单词“正常”,rest 保持中立。
Does anyone know what may be happening to both codes?有谁知道这两个代码可能会发生什么?
Does anyone know what may be happening to both codes?
有谁知道这两个代码可能会发生什么?
Code 1:代码 1:
You made a typo, lenght
should be length
.你打错了,
lenght
应该是length
。
Code 2:代码 2:
See my answer below.请看下面我的回答。
You need to iterate over all elements with the particular keyword.您需要使用特定关键字遍历所有元素。
To achieve that you need to follow these steps:为此,您需要执行以下步骤:
get the first found element:获取第一个找到的元素:
pinkElement = body.findText(searchWord);
check if an element with searchWord
exists检查是否存在带有
searchWord
的元素
do some code for this element为这个元素做一些代码
assign a new element which is the next one you found before:分配一个新元素,它是您之前找到的下一个元素:
pinkElement = body.findText(searchWord, pinkElement);
repeat steps 1-4 until there is no other element:重复步骤 1-4,直到没有其他元素:
while (pinkElement != null)
function myFunction() {
let doc = DocumentApp.getActiveDocument();
let body = doc.getBody();
let pinkColor = "#FFC0CB";
let searchWord = "Normal";
let pinkElement = body.findText(searchWord);
while (pinkElement != null) {
let elem = pinkElement.getElement().asText();
let t = elem.getText();
elem.setForegroundColor(t.indexOf(searchWord), t.indexOf('High')+3, pinkColor);
pinkElement = body.findText(searchWord, pinkElement);
}
}
I'm surprised it is returning the first one.我很惊讶它正在返回第一个。 "length" is spelled wrong on this line:
“长度”在这一行拼写错误:
for (i=0; i<paras.**lenght**; i++) {
See if changing it to ".length" fixes it.看看是否将其更改为“.length”可以修复它。 If not, there is a similar example in the Docs at Class Range you could use.
如果没有,您可以使用Class Range的文档中的类似示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.