You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用App Script在Google Docs中选中空行并设置为红色

实现方案

Google Docs 的 findText 方法仅匹配文本元素内的可见字符,换行属于段落分隔符,不属于文本内容,所以你尝试搜索 \n 或 <br> 无法准确匹配目标,传入空串调用 findText 会匹配所有文本内容,导致全局变红。

你可以参考下面的代码实现仅将下划线和空行换行设为红色的需求:

function redLine() {
  const body = DocumentApp.getActiveDocument().getBody();

  // 匹配所有下划线字符并设为红色
  let underlineMatch = body.findText("_");
  while (underlineMatch) {
    const textElem = underlineMatch.getElement().asText();
    const start = underlineMatch.getStartOffset();
    const end = underlineMatch.getEndOffsetInclusive();
    textElem.setForegroundColor(start, end, "#FF0000");
    underlineMatch = body.findText("_", underlineMatch);
  }

  // 匹配所有空段落(空行换行)并设为红色
  const paragraphs = body.getParagraphs();
  paragraphs.forEach(para => {
    if (para.getText().trim() === "") {
      para.setForegroundColor("#FF0000");
    }
  });
}

额外适配说明

如果你需要标记的是带下划线格式的文本,而非_字符,可以把下划线匹配的逻辑替换为以下代码:

// 匹配所有带下划线格式的文本并设为红色
const rangeElems = body.getRangeElements();
rangeElems.forEach(item => {
  const elem = item.getElement();
  if (elem.getType() !== DocumentApp.ElementType.TEXT) return;
  const text = elem.asText();
  const textLen = text.getText().length;
  for (let i = 0; i < textLen; i++) {
    if (text.isUnderline(i)) {
      text.setForegroundColor(i, i, "#FF0000");
    }
  }
});

内容的提问来源于stack exchange,提问作者itr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:36:08