如何编写Google Apps Script函数批量设置文档中%字符为灰色
批量修改Google Docs中%字符颜色的解决方案
操作步骤
- 打开目标Google文档,点击顶部菜单栏「扩展程序」>「Apps 脚本」,进入脚本编辑器。
- 替换默认代码为以下脚本:
function formatPercentCharacters() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const targetChar = "%"; let match = body.findText(targetChar); while (match) { const element = match.getElement(); const start = match.getStartOffset(); const end = match.getEndOffsetInclusive(); // 将匹配的%字符设置为灰色(#cccccc) element.setForegroundColor(start, end, "#cccccc"); // 查找下一个匹配项 match = body.findText(targetChar, match); } }
- 在脚本编辑器的函数下拉框中选择
formatPercentCharacters,点击运行按钮(▶️),首次运行需按提示完成权限授权。
代码说明
- 通过
DocumentApp.getActiveDocument()获取当前文档实例 - 使用
findText方法定位所有%字符,循环遍历每一个匹配结果 - 调用
setForegroundColor为匹配的字符区间设置灰色,处理完一个匹配项后继续查找下一个,直到无匹配结果为止
该脚本仅执行一次,运行完成后所有%字符会统一变为灰色。
内容的提问来源于stack exchange,提问作者Jared Evans
相关产品推荐
相关产品推荐

