Home > Mobile >  How can I link the current Google Doc to a new Google Doc named with the text on the line where the
How can I link the current Google Doc to a new Google Doc named with the text on the line where the

Time:06-13

Here's a sample use case.

  1. Let say I were typing in Google Doc #1, and then
  2. 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).
  3. Furthermore, let's say I would this new Google Doc (which does not yet exist) to be named "Cherry pie."
  4. Therefore, while I was in Google Doc #1, I would type "Cherry pie", and then
  5. I would run the script.
  6. 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())
  • Related