0

I need to get all hyperlinks in the document and then delete the text to which hyperlink is attached and insert new test. Here is a sample of what I want

sample of my requirement

I got a lot of resources, solutions and new thing to learn while solving this problem and currently I like using Google Doc API method. Here are the steps I need to complete the task.

  1. Get the hyperlink text using textrun.content
  2. Get the indexes of hyperlink text given in element array
  3. Copy hyperlink and its text to a variable
  4. Delete hyperlink text
  5. Modify the hyperlink variable according to need
  6. Insert new variable value to the same index in document

I am stuck at STEP 4, when I try to delete hyperlink text it deletes some of hyperlinks and leaves some others. Here is the code that I tried;

function myFunction() {
    const doc = DocumentApp.getActiveDocument();
    const res = Docs.Documents.get(doc.getId()).body.content.reduce((ar , {paragraph}) => {
      if (paragraph && paragraph.elements) {
        paragraph.elements.forEach(({textRun,startIndex, endIndex}) => {
          if (textRun && textRun.textStyle && textRun.textStyle.link) {
            console.log(textRun.content);
            requests = [
                    {
                        'deleteContentRange': {
                            'range': {
                                'startIndex': startIndex,
                                'endIndex': endIndex,
                            }

                        }

                    },
                ]
            Docs.Documents.batchUpdate({'requests': requests}, DocumentApp.getActiveDocument().getId());
          }
        });
      }
    }, []);
  }

Upon digging further into the problem I find this section which shows the rules of deletion and this might be causing trouble here.

How can I achieve my goal? Here is the shared document I am working on.

James Z
  • 12,209
  • 10
  • 24
  • 44
abdulsamad
  • 158
  • 1
  • 10
  • Can you clarify what you mean by `when I try to delete hyperlink text it deletes some of hyperlinks and leaves some others`? – Rafa Guillermo Jan 11 '21 at 09:49
  • I mean when I try the code it deletes some hyperlinks but not all, you can check the code above to see the effect. I have also shared a document on which this error is happening. – abdulsamad Jan 11 '21 at 13:38
  • Can you provide a screenshot(s) or gif of what you mean? – Rafa Guillermo Jan 11 '21 at 13:42
  • 1
    Your end format looks a lot like another user in a recent question. https://stackoverflow.com/questions/18727341/get-all-links-in-a-document – aNewb Jan 15 '21 at 01:45

0 Answers0