I don't believe I changed my code, yet it doesn't work anymore. Did Apps Script change something? I enabled the Drive API and tried both the legacy editor and the new editor.
I'm trying to replace links in multiple Google Docs within a folder. Below is a snippet of the code but I have 50+ links.
function myFunction() {
var oldLinkText = "Casarett and Doull’s Essentials of Toxicology, 3e";
var newLinkText = "Casarett & Doull’s Essentials of Toxicology, 4e";
var oldLinkURL = "accesspharmacy.mhmedical.com/book.aspx?bookID=1540";
var newLinkURL = "accesspharmacy.mhmedical.com/Book.aspx?bookid=3000";
var oldLinkText2="Harrison's Principles of Internal Medicine, 19e";
var newLinkText2="Harrison's Principles of Internal Medicine, 20e";
var oldLinkURL2="accessmedicine.mhmedical.com/book.aspx?bookid=1130";
var newLinkURL2="accessmedicine.mhmedical.com/book.aspx?bookid=2129";
var oldLinkText3="Behavioral Medicine: A Guide for Clinical Practice, 4e";
var newLinkText3="Behavioral Medicine: A Guide for Clinical Practice, 5e";
var oldLinkURL3="accessmedicine.mhmedical.com/book.aspx?bookID=1116";
var newLinkURL3="accessmedicine.mhmedical.com/book.aspx?bookid=2747";
var files = DriveApp.getFolderById("folderID").getFilesByType(MimeType.GOOGLE_DOCS);
while (files.hasNext()) {
var file = files.next();
if(file){
var doc = DocumentApp.openById(file.getId());
var link=doc.getBody().findText(oldLinkText);
var link2=doc.getBody().findText(oldLinkText2);
var link3=doc.getBody().findText(oldLinkText3);
}
}
if(link){
link=link.getElement().asText();
link.setLinkUrl(newLinkURL);
doc.replaceText(oldLinkText, newLinkText);
}
if(link2){
link2=link2.getElement().asText();
link2.setLinkUrl(newLinkURL2);
doc.replaceText(oldLinkText2, newLinkText2);
}
if(link3){
link3=link3.getElement().asText();
link3.setLinkUrl(newLinkURL3);
doc.replaceText(oldLinkText3, newLinkText3);
}
Logger.log("Done")
}
I used the code on one file and it worked, but I was trying to get it to work on multiple Google Docs files within a Google Drive folder. It kept stopping at one. In other words, it would look at the first file in the folder, and would stop looking if it didn't find the text in that file. It ignored the other files in the Google Drive folder.
I changed two things in the code and now it worked. I removed the two curly brackets before "if(link){" and put them at the very end of the code. I also changed ".getFilesByType(MimeType.GOOGLE_DOCS);" to just ".getFiles();"