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

回眸只為那壹抹淺笑 提交于 2019-12-11 16:54:30

问题


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")
}

回答1:


You need to replace both the text and the hyperlink separately

The hyperlink can be modfied 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")
}


来源:https://stackoverflow.com/questions/57819771/how-to-replace-url-within-hyperlinks-in-multiple-google-docs-with-a-google-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!