Here's a sample use case.
- Let say I were typing in Google Doc #1, and then
- I were to decide that I would like to create a link in Google Doc #1 to a new Google Doc (which does not yet exist).
- Furthermore, let's say I would this new Google Doc (which does not yet exist) to be named "Cherry pie."
- Therefore, while I was in Google Doc #1, I would type "Cherry pie", and then
- I would run the script.
- As a result, in Google Doc #1 the line where the cursor is currently located (which consists of "Cherry pie") would now be hyperlinked to the Google Doc (which the script just created) named "Cherry pie."
When I run the script below in Google Doc #1, it creates a new Google Doc (Google Doc #2). The script names Google Doc #2 with the text of the line where the cursor is currently located in Google Doc #1.
For example, if the cursor is on a line in Google Doc #1 with the text "Cheese pizza", then the script will create a new Google Doc named "Cheese pizza."
In addition to what the script currently does, I would like the script to also create a hyperlink from "Cheese pizza" (on the line where the cursor is currently located) in Google Doc #1 to Google Doc #2 (which is the document the script will create) with the name "Cheese pizza."
function onOpen(e) {
DocumentApp.getUi().createMenu('NewDoc')
.addItem('Create', 'newDocWithSentense')
.addToUi();
}
function newDocWithSentense() {
const doc = DocumentApp.getActiveDocument();
const cursor = doc.getCursor();
const surroundings = cursor.getSurroundingText().getText();
const currentFileFolder = DriveApp.getFileById(doc.getId()).getParents().next()
const newDoc = DocumentApp.create(surroundings).getId()
DriveApp.getFileById(newDoc).moveTo(currentFileFolder)
}
CodePudding user response:
I believe what you're looking for is Text.setLinkUrl()
Since cursor.getSurroundingText()
returns a Text
object, you can add this line at the end of your existing code:
cursor.getSurroundingText().setLinkUrl(DriveApp.getFileById(newDoc).getUrl())