Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

Deleting hyperlink and its text using Google Doc API

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.

question from:https://stackoverflow.com/questions/65645463/deleting-hyperlink-and-its-text-using-google-doc-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...