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
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.
- Get the hyperlink text using textrun.content
- Get the indexes of hyperlink text given in element array
- Copy hyperlink and its text to a variable
- Delete hyperlink text
- Modify the hyperlink variable according to need
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…