Jon Robbins
Jon Robbins

Reputation: 1

How to replace URL within hyperlinks in multiple Google Docs with a Google Apps script

Background: I have about 1500 Google Docs in a Google Services account shared directory. Some of those docs have hyperlinks. I need to replace the URL in hyperlinks with new URLs using a Google Script.

I found this script here. The script below will successfully replace URL's within the body of any Google Doc in my drive, but it will not replace any URL's within hyperlinks.

How can I modify this script to replace the URL within a hyperlink instead of just the body text?

  var files = DriveApp.getFiles();   // Note: this gets *every* file in your Google Drive
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    var doc = DocumentApp.openById(file.getId());
    doc.replaceText("http://www.googledoclink1.com", "http://www.googledoclinkA.com");
    doc.replaceText("http://www.googledoclink2.com", "http://www.googledoclinkB.com");// Note: This will be repeated probably 500 times
  }
  Logger.log("Done")
}

Upvotes: 0

Views: 2189

Answers (1)

ziganotschka
ziganotschka

Reputation: 26796

You need to replace both the text and the hyperlink separately

The hyperlink can be modified with setLinkUrl().

Modify your code in a following way to make it work:

function myFunction() {
  var oldLink="http://www.googledoclink1.com";
  var newLink="http://www.googledoclinkA.com";
  var oldLink2="http://www.googledoclink2.com";
  var newLink2="http://www.googledoclinkB.com";
  var files = DriveApp.getFiles();   // Note: this gets *every* file in your Google Drive
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    var doc = DocumentApp.openById(file.getId());
    var link=doc.getBody().findText(oldLink).getElement().asText(); 
    var link2=doc.getBody().findText(oldLink2).getElement().asText(); 
    link.setLinkUrl(newLink);   
    doc.replaceText(oldLink, newLink);
    link2.setLinkUrl(newLink2);   
    doc.replaceText(oldLink2, newLink2);
  }
  Logger.log("Done")
}

Upvotes: 3

Related Questions