Google Apps 脚本 - 替换文本的最佳方式

Google Apps Scripts - Optimal way to replace text

我需要在 Google 文档中替换大量字符串。我对 运行 我的剧本的表现受到了巨大的打击,并且永远持续到 运行 现在。我正在研究如何优化。

body.replaceText("oldvalue1",newValue1)
body.replaceText("oldvalue2",newValue2)
body.replaceText("oldvalue3",newValue3)
..
..
..

是否有更优化的方法来使用 google 脚本替换 Google 文档中的文本?

Array.forEach(obj => { body.replaceText(obj.old,obj.new)})

@kos 方式可能是更好的方式。

作为 @Kos refers in the comments, the best approximation is using Google Docs API batchUpdates as Advanced Service 在 Google Apps 脚本中。

我给你举了一个例子,说明 Docs API 如何作为高级服务工作。对于这个例子,我假设你有一个对象数组,其中包含 oldValuenewValue:

function batchUpdating(DocID = DocID) {
  const replaceRules = [
    {
      toReplace: "oldValue1",
      newValue: "newValue1"
    },
...
  ]
  const requestBuild = replaceRules.map(rule => {
    var replaceAllTextRequest = Docs.newReplaceAllTextRequest()
    replaceAllTextRequest.replaceText = rule.newValue
    replaceAllTextRequest.containsText = Docs.newSubstringMatchCriteria()
    replaceAllTextRequest.containsText.text = rule.toReplace
    replaceAllTextRequest.containsText.matchCase = false
    Logger.log(replaceAllTextRequest)
    var request = Docs.newRequest()
    request.replaceAllText = replaceAllTextRequest
    return request
  })
  var batchUpdateRequest = Docs.newBatchUpdateDocumentRequest()
  batchUpdateRequest.requests = requestBuild
  var result = Docs.Documents.batchUpdate(batchUpdateRequest, DocID)
  Logger.log(result)
}

Google Apps 脚本帮助我们处理授权流程,并为我们提供有关如何构建请求的提示。例如,Docs.newReplaceAllTextRequest() 帮助我们构建该服务的请求,提示我们它包含 replaceTextcontainText。无论如何,我们也可以直接将对象提供给请求:

const requestBuild = replaceRules.map(rule => {
    return {
      replaceAllText:
      {
        replaceText: rule.newValue,
        containsText: { text: rule.oldValue, matchCase: false }
      }
    }
})
考虑

Each request is validated before being applied. If any request is not valid, then the entire request will fail and nothing will be applied.

If your script project uses a default GCP project created on or after April 8, 2019, the API is enabled automatically after you enable the advanced service and save the script project. If you have not done so already, you may also be asked to agree to the Google Cloud Platform and Google APIs Terms of Service as well.

文档: