Edits history of script submission #23023 for ' Replace Text (gdocs)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Replace Text
     * 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.
     */
    export async function main(
      auth: RT.Gdocs,
      document_id: string,
      find: string,
      replace: string,
      match_case: boolean = true
    ) {
      const response = await fetch(
        `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${auth.token}`,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            requests: [
              {
                replaceAllText: {
                  containsText: { text: find, matchCase: match_case },
                  replaceText: replace,
                },
              },
            ],
          }),
        }
      )
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      return await response.json()
    }
    

    Submitted by hugo989 4 hours ago