如何使用Google Apps脚本替换多个Google文档中超链接中的URL [英] How to replace URL within hyperlinks in multiple Google Docs with a Google Apps script

查看:90
本文介绍了如何使用Google Apps脚本替换多个Google文档中超链接中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我在一个Google Services帐户共享目录中有大约1500个Google文档.其中一些文档具有超链接.我需要使用Google脚本用新的URL替换超链接中的URL.

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.

我在此处找到了该脚本.以下脚本将成功替换驱动器中任何Google Doc正文中的URL,但不会替换超链接中的任何URL.

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.

如何修改此脚本以替换超链接中的URL,而不仅仅是正文?

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

推荐答案

您需要分别替换文本和超链接

可以使用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")
}

这篇关于如何使用Google Apps脚本替换多个Google文档中超链接中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆