Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

check if portion of paragraph is hyperlinked in Google doc

This is how I select my paragraph in my Google doc

let document = DocumentApp.getActiveDocument().getBody();
let paragraphs = document.getParagraphs();
let paragraph = paragraphs[5];

Now how do I check if there is a URL linked on the portion of the paragraph from index/position start to end?

For example, if the paragraph were

Hello darkness my old friend

then it should return true for the positions 19 to 23 because that portion of text links to stackoverflow.

There is the method paragraph.editAsText().getLinkUrl() but it doesn't take the indices/positions as parameters.

Please help

question from:https://stackoverflow.com/questions/65907400/check-if-portion-of-paragraph-is-hyperlinked-in-google-doc

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

1 Answer

0 votes
by (71.8m points)

Try this:

function findURL() {
  var document = DocumentApp.getActiveDocument().getBody();
  var paragraphs = document.getParagraphs();
  var text = paragraphs[0].getText();
  var child = paragraphs[0].getChild(0).asText();
  //Storing words in an array
  var words = text.match(/S+/g);
  //check if array is empty
  if (words) {
    //iterate each words
    words.forEach(word => {
      //use findtext and getStartOffset to find the start position of string
      //use getLinkUrl(offset) to check if the word has link on it.
      if(child.getLinkUrl(child.findText(word).getStartOffset())){
        //print the position of words that has link.
        //added +1 since the start of count in getStartOffset() is zero.
        Logger.log(child.findText(word).getStartOffset()+1);
      }
    })
  }
}

Example:

enter image description here

Output:

enter image description here

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...