title: Easiest way to get file ID from URL on Google Apps Script
body: <p>Here is what I'm trying to do: given a Google document URL, I want to get the document ID to create a copy on Google Drive. I know I can achieve that by some regex or replacing on the URL, but as there are several different forms to represent the same document in a URL, I wanted to find a generic solution.</p>
  
  <p>Currently, that's the best I could think:</p>
  
  <pre><code>function getFileIdFromUrl(url) {
    try {
      return getDocIdFromUrl(url);
    } catch (e) {
      return getSpreadsheetIdFromUrl(url);
    }
  }
  
  function getDocIdFromUrl(url) {
    var doc = null;
    try {
      doc = DocumentApp.openByUrl(url);
    } catch (e) {
      doc = DocumentApp.openByUrl(url + "/edit");
    }
    return doc.getId();
  }
  
  function getSpreadsheetIdFromUrl(url) {
    var spreadsheet = null;
    try {
      spreadsheet = SpreadsheetApp.openByUrl(url);
    } catch (e) {
      spreadsheet = SpreadsheetApp.openByUrl(url + "/edit");
    }
    return spreadsheet.getId();
  }
  
  function copy(url) { // may throw an exception if the URL is invalid or private
     var id = getFileIdFromUrl(url);
     var file = DriveApp.getFileById(id);
     file.makeCopy().setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  }
  </code></pre>
  
  <p>The problem is that my solution only covers documents and spreadsheets, I would like to do the same with any uploaded file, for example:</p>
  
  <p><a href="https://docs.google.com/file/d/0B-FYu_D7D7x4REdtRVEzVH0eU0/edit">https://docs.google.com/file/d/0B-FYu_D7D7x4REdtRVEzVH0eU0/edit</a></p>
  
  <p>In short, I wanted something like that:</p>
  
  <pre><code>DriveApp.getFileByUrl(url).makeCopy();
  </code></pre>
  
  <p>Does anyone know if it's possible?</p>
  
  <p>Any safe solution to extract the file ID from the file URL would fit as well for me.</p>
  
  <p>Thanks</p>