Search code examples
google-apps-scriptgoogle-docsgoogle-docs-api

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


Solution

  • 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: