I have a block of text generated from a command line script which spins up a number of virtual machines. The text output contains instructions on how to access webapps on the virtual machines, so something like:
TrainingMachine01
Username: [user]
Password: [pass]
iPython: http://ip/
RStudio: http://ip:8787/
I take this text and dump it into a Google Doc which is shared with a number of people (we run courses in Python and R, and spin up a VM for each attendee).
I would like to be able to format my output as hyperlinks, so that the attendees only need to click on the URL rather than copy it and paste it into a browser (firstworldproblems).
After investigating ways of pasting text into Google Docs, I don't think there's a simpler solution than a Google Apps script, which would simply find patterns matching a URL, and make them hyperlinks.
Here's what I have so far, based in large part on this answer to another question:
function updateLinks() {
// Open active doc
var body = DocumentApp.getActiveDocument().getBody();
// Find URLs
var link = body.findText("http:\/\/.*\/");
// Loop through
while (link != null) {
// Get the link as an object
var foundLink = link.getElement().asText();
// Get the positions of start and end
var start = link.getStartOffset();
var end =link.getEndOffsetInclusive();
// Format link
foundLink.setLinkUrl(start, end, foundLink);
// Find next
link = body.findText("http:\/\/.*\/", link);
}
}
My pattern and loop are working fine, except the URL that's being written into the hyperlink is either http://text
if I use foundLink
in the Format link section, or http://rangeelement
if I use the link
var.
How can I have the script set the URL as the text itself?
(New to Javascript and have been using exercises like this to learn it and Google Apps Script)
Update: a-change's comment pointed me to the getText()
method on text elements, so that the relevant line becomes foundLink.setLinkUrl(start, end, foundLink.getText());
. However this is still not quite working, and is inserting links pointing to about:blank
. Any ideas how to sanitise the text extracted from findText()
?