Extract multiple links from one Google Sheet cell and then paste them in a Google Doc as hyperlinks using Google Apps Script

Viewed 600

I would like to do the following with Google Apps Script:

  1. Search an specific cell in Google Sheets with multiple URL's
  2. Split the URL's and get them as separate links in order to avoid using the split function in sheets (watch the image
  3. Attach each URL into a Google Doc by using tags

I've done this before, but I'm only able to obtain the URL's in one array and not separated (watch image 1 and image 2)

for (var i=0; i<row[rownumber].length; i++){
  if (row[rownumber].includes(",")) 
  img=row[rownumber].split(",");
  body.replaceText('{{TagName}}',img);
}

Here you have the example in Google Sheets in order to apply the mentioned steps (link). Any help would be appreciated. Thanks!

1 Answers

You can refer to this sample code:

  var doc = DocumentApp.openById('YourDocId');   
  var body = doc.getBody();

  var sheet = SpreadsheetApp.getActiveSheet();
  var rowValues = sheet.getRange(1,1,sheet.getLastRow(),1).getValues().flat();

  //Combine all row values into a single url array
  var urls = [];
  rowValues.forEach(row => {

    if(row.includes(",")){
      var tmp = row.split(",");
      urls = urls.concat(tmp);
    }
  });

  Logger.log(urls);
  Logger.log(urls.length);
  
  if(urls.length > 0){
    var tag = "{{TagName}}";
    var newLine = "\n\n";

    var element = body.findText(tag);
    if(element){ // if found a match
        var start = element.getStartOffset();
        var text = element.getElement().asText();
        //remove tag in the docs
        text.deleteText(start,start+tag.length-1);

        //Add url
        urls.forEach(url => {
          url = url.trim(); //remove whitespaces on both ends of the url string
          Logger.log("START: "+start);
          Logger.log(url);
          Logger.log("URL LENGTH: "+url.length);
          text.appendText(url).setLinkUrl(start, start+url.length-1, url);
          text.appendText(newLine);
          start = start + url.length + newLine.length;
          Logger.log(text.getText());
          Logger.log("*****");
        });
        doc.saveAndClose();
    }
  }

Note: You can remove the logs if you felt like you don't need them. I just used them to debug the code.

What it does?

  1. Get the url links from column A starting row 1 up to the last available row.
  2. Parse each row. Split the url string into individual urls' then concatenate it to urls array.
  3. Find your tag to be replaced in the document's body using Body.findText(searchPattern)
  4. Get the start offset of the matched text using RangeElement.getStartOffset()
  5. Get the element that corresponds to the RangeElement using RangeElement.getElement()
  6. Get the element as text using Element.asText()
  7. Delete the tag string in your document using Text.deleteText(startOffset, endOffsetInclusive)
  8. Loop each url in the array.Take note to remove whitespaces in the current url string. Add the url text using Text.appendText(text). Once the url text was appended, include it's url link using Text.setLinkUrl(startOffset, endOffsetInclusive, url). Add a new line using Text.appendText(text) then adjust the start offset based on the url length and the new line length. (Repeat until all the url links were added in the document)

Output:

enter image description here

(UPDATE:)

If you want to give a different name in your hyperlink, you can replace the appended text and modify the offsets in the setLinkUrl()

Sample Code Changes:

        //Add url
        urls.forEach((url, index) => {
          url = url.trim(); //remove whitespaces on both ends of the url string
          var name = "Image"+(index+1);
          Logger.log("START: "+start);
          Logger.log(url);
          Logger.log("URL LENGTH: "+url.length);
          Logger.log("NAME LENGTH: "+name.length);
          text.appendText(name).setLinkUrl(start, start+name.length-1, url);
          text.appendText(newLine);
          start = start + name.length + newLine.length;
          Logger.log(text.getText());
          Logger.log("*****");
        });

Output:

enter image description here

Related