我是google文档脚本的新手。
在google中,我需要搜索几个文本字符串(例如,轻型字体中的“学生1”),以便将这些文本字符串替换为另一个文本字符串(例如,"Student “),但使用粗体字体。
要搜索和替换,我使用以下代码:
function docReplace() {
var body = DocumentApp.getActiveDocument().getBody();
// change "student 1" to "Student A" in boldface
body.replaceText("student 1", "Student A");
}
上面的代码只将“学生1”替换为“学生A”,使用当前的google字体,但我不知道如何将字体从光明面改为粗体字体。
我试过了
body.replaceText("student 1", "<b>Student A</b>");
当然,上面的代码不起作用。
任何帮助都将不胜感激。谢谢。
发布于 2015-10-19 19:30:15
用新的文本字符串(例如,“学生会A")替换在google中多次出现的文本字符串(例如,”学生1")的普通方法是两个步骤:
1-编写一个函数(例如,docReplace)来进行搜索并替换为常规/普通字体(没有黑体字):
function docReplace() {
var body = DocumentApp.getActiveDocument().getBody();
// change "student 1" to "Student A"
body.replaceText("student 1", "Student A");
}
2-编写一个函数(例如,boldfaceText)来搜索所需的文本(例如,“学生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);
}
}
boldfaceText的上述代码是从post 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");
}
在google中,只需运行脚本docReplace就可以将所有出现的“学生1”改为“学生会A”。
以上两个函数(docReplace和boldfaceText)可以很好地将新手(比如我)介绍给google脚本。在玩了一段时间的google脚本以获得一些熟悉之后,学习Robin的更优雅和更高级的代码,它同时完成了上述两个步骤。
发布于 2015-10-19 09:05:43
用另一个字符串替换一个字符串可以通过简单的查找和替换来完成。
设置它们粗体有点困难,因为您必须获得正文的文本元素,还必须找到每个出现的单词的开始和结束位置。
由于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);
}
}
https://stackoverflow.com/questions/33205269
复制相似问题