0

Replace Text

by
Published today

Replace every occurrence of a string in a Google Doc.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
/**
4
 * Replace Text
5
 * Replace every occurrence of a string in a Google Doc (all tabs) — handy for filling `{{placeholder}}` templates. The response's `replies[0].replaceAllText.occurrencesChanged` says how many matches were replaced.
6
 */
7
export async function main(
8
  auth: RT.Gdocs,
9
  document_id: string,
10
  find: string,
11
  replace: string,
12
  match_case: boolean = true
13
) {
14
  const response = await fetch(
15
    `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
16
    {
17
      method: "POST",
18
      headers: {
19
        Authorization: `Bearer ${auth.token}`,
20
        "Content-Type": "application/json",
21
        Accept: "application/json",
22
      },
23
      body: JSON.stringify({
24
        requests: [
25
          {
26
            replaceAllText: {
27
              containsText: { text: find, matchCase: match_case },
28
              replaceText: replace,
29
            },
30
          },
31
        ],
32
      }),
33
    }
34
  )
35
  if (!response.ok) {
36
    throw new Error(`${response.status} ${await response.text()}`)
37
  }
38

39
  return await response.json()
40
}
41