Google-apps-script – Automatically create link when pasting URL in Google Docs

google docsgoogle-apps-script

Long story short, I regularly paste batches of hyperlinks into Google Docs. When they're copied, they're unlinked and purely raw text. When pasting it into Google Docs however, those links (understandably) don't come up as links, and I have to manually link each one.

Is there a short way for Google Docs to automatically change all "hyperlink-looking" text to hyperlinks?

EDIT:
Here's the type of things I'm copy-pasting into Google Docs every week:

text
text
text
link

text
text
text
link

etc. (x20)

I already have http:// in front of each link, but since I'm pasting the whole block into Google Docs, it doesn't automatically convert. I'm looking for a way to highlight the whole document, press a button, and change all "link-eligible" text into links.

Best Answer

the pattern matching for identifying a link is very basic but this should get you started. It will add a menu to your doc that will look at all highlighted text and make links where it should. (past into script editor, save the script. reload the doc)

the major part of this was modified from this example: https://developers.google.com/apps-script/reference/document/range

function onOpen(e) {
   DocumentApp.getUi()
       .createMenu('My Menu')
       .addItem('make links', 'test')
       .addToUi();
 }


function test(){
var selection = DocumentApp.getActiveDocument().getSelection();
 if (selection) {
   var elements = selection.getRangeElements();
   for (var i = 0; i < elements.length; i++) {
     var element = elements[i];

     // Only modify elements that can be edited as text; skip images and other non-text elements.
     if (element.getElement().editAsText) {
       var text = element.getElement().editAsText();

       if (text.findText("http")){
        text.setLinkUrl(text.getText() )
       }
     }
   }
 }
}