Tuesday 30 November 2021

Replace text in a Google Doc with a hyperlink

The following Google Apps Script is designed to search the body of a Google Doc for a specific string/pattern (ie a keyword I have used) and insert a clickable hyperlink. Typically I use the JavaScript replace method when going through the body of a Doc and inserting data. However I recently came across a difficulty where I was inserting data into a table that was causing the long hyperlinks to split between 2 lines and hence lose their click functionality. With full credit to this blog post by Yagisanatode I found a way to overcome this.

Starting in the usual manner we pick-up our Google Doc and get its body, so that we can start to work on the content:

var docBody = DocumentApp.openById('Doc ID here').getBody();

Now we look to use the 'findText' method to search the content for our string/pattern. From this we are returned the position (range) and need to 'getElement' with 'asText' so that it can be edited:

var getString = docBody.findText("<<keyword>>").getElement().asText();

Finally we can set the text that will be displayed in the Google Doc in replace of our keyword along with our hyperlink for when a user clicks on it:

getString.setText("Useful link to click").setLinkUrl("www.pbainbridge.co.uk");

No comments:

Post a Comment