Created
January 8, 2022 21:15
-
-
Save vladox/f8cd873571ffa8038fb15175a476f20b to your computer and use it in GitHub Desktop.
Google Docs hyperlinks search & replace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var oldLink = "https://your-old-link-here"; | |
var newLink = "https://your-new-link-here"; | |
var documentId = 'YOUR-GOOGLE-DOCUMENT-ID-HERE'; | |
var doc = DocumentApp.openById(documentId); | |
var searchType = DocumentApp.ElementType.TEXT; | |
function findAndReplaceLinks() { | |
var body = doc.getBody(); | |
var text = body.getText(); | |
var searchResult = null; | |
var searchResultTextElement = null; | |
var searchResultText = ""; | |
while (searchResult = body.findElement(searchType, searchResult)) { | |
searchResultTextElement = searchResult.getElement().asText(); | |
searchResultText = searchResultTextElement.getText(); | |
// Logger.log("TEXT: %s", searchResultText); | |
var words = searchResultText.match(/\S+/g); | |
if (words) { | |
words.map(function (e) { | |
// sanitize search terms for regex relevent symbols | |
e = e.replaceAll("(", "\\(").replaceAll(")", "\\)").replaceAll("+", "\\+").replaceAll("*", "\\*"); | |
e = e.replaceAll("[", "\\[").replaceAll("]", "\\]").replaceAll("{", "\\{").replaceAll("}", "\\}"); | |
// Logger.log("WORD: %s", e); | |
var partialElementUrl = null; | |
if (e.trim() != "") { | |
var partialElement = searchResultTextElement.findText(e); | |
var partialElementText = partialElement.getElement().asText(); | |
var startOffset = partialElement.getStartOffset(); | |
var endOffsetInclusive = partialElement.getEndOffsetInclusive(); | |
partialElementUrl = searchResultTextElement.getLinkUrl(partialElement.getStartOffset()); | |
if (partialElementUrl != null) { | |
var updatedUrl = partialElementUrl.replace(oldLink, newLink); | |
if (partialElementUrl.includes(oldLink)) { | |
Logger.log("REPLACING WORD: %s AT OFFSET: %s", partialElementText.getText().substring(startOffset, endOffsetInclusive + 1), startOffset); | |
partialElementText.setLinkUrl(startOffset, endOffsetInclusive, updatedUrl); | |
} else if (partialElementUrl.includes(newLink)) { | |
Logger.log("ALREADY REPLACED WORD: %s", partialElementUrl); | |
} | |
} | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment