0

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")
}
2
  • What do you mean by replacing a URL within a hyperlink? Could do provide a sample Docs file showing what should be change to what? Commented Sep 6, 2019 at 11:10
  • I mean a URL within the body text was replaced successfully by the script. A URL within a hyperlink (e.g. "Click here!" with the URL embedded) was not replaced by the script above. Here's a sample doc: docs.google.com/document/d/… Commented Sep 6, 2019 at 16:20

1 Answer 1

3

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")
}
Sign up to request clarification or add additional context in comments.

1 Comment

See my solution for a document wide search & replace (only hyperlinks): stackoverflow.com/a/70636525/164374

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.