Google Docs – Paste Href Tag as Link

google docs

I have a Google document. When I copy and paste something from my browser to the document, the text with hyperlinks get translated into hyperlinks in the document.

If I am in emacs or vim and copy html code into the document, Google treats it like text. This is a reasonable assumption. However I'm wondering if there's a way to trick Google into thinking that a href tag should be turned into a hyperlink.

Best Answer

There are no tricks, just built-in tools and scripts.

Manual conversion

To turn http://example.com into http://example.com, select it and press Ctrl-K (or right-click and choose Link).

This will be a hassle if you pasted in several dozens of these. Then a script is preferable.

Conversion with a script

I wrote two functions, for two different conversions:

  • <a href="http://example.com">link text</a> to <a href="http://example.com">link text</a>
  • <a href="http://example.com">link text</a> to link text

Both are added to the document menu by the onOpen function.

The approach is the same in both cases, the details vary in step 3.

  1. Use Body.findText method to find the elements containing the text of interest. (This search method has some support of regular expressions, although not much.)
  2. Obtain the text string from each matching element: .getElement().asText().getText()
  3. Use the JavaScript regex engine to search (and substitute if necessary).
  4. Finally, linkify by using Text.setLinkUrl method.
function linkify() {
  var body = DocumentApp.getActiveDocument().getBody();
  var range = body.findText("<a[^<]*</a>");
  while (range) {  
    var nextRange = body.findText("<a[^<]*</a>", range);
    var elem = range.getElement().asText();
    var str = elem.getText();
    var re = /href=(\W)(.*?)\1/g;
    var result = re.exec(str); 
    while (result) {
      var index = result.index; 
      var url = result[2]; 
      elem.setLinkUrl(index+6, index+url.length+5, url);
      result = re.exec(str);
    }
    range = nextRange;
  }
}

function replaceWithLink() {
  var body = DocumentApp.getActiveDocument().getBody();
  var range = body.findText("<a[^<]*</a>");
  while (range) {  
    var nextRange = body.findText("<a[^<]*</a>", range);
    var elem = range.getElement().asText();
    var str = elem.getText();
    var result = /<a[^<]*<\/a>/.exec(str); 
    while (result) {
      var link = result[0];
      var index = result.index;
      var url = /href=(\W)(.*)\1/.exec(link)[2];
      var text = />(.*)</.exec(link)[1];
      elem.replaceText(link, text);
      elem.setLinkUrl(index, index+text.length-1, url);
      str = str.replace(link, text);
      result = /<a[^<]*<\/a>/.exec(str);
    }
    range = nextRange;
  }
}

function onOpen() {
  DocumentApp.getUi()
             .createMenu('Custom')
             .addItem('Recognize href as a link', 'linkify')
             .addItem('Replace <a> elements with links', 'replaceWithLink')
             .addToUi();
}