The easiest way to get a file id from a URL in Google Apps Script

Here's what I'm trying to do: given the Google URL, I want to get the ID of the document to create a copy in Google Drive. I know that I can achieve this with some regular expression or replace the URL, but since there are several different forms for representing the same document in the URL, I wanted to find a general solution.

This is currently the best I could think of:

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); } 

The problem is that my solution only covers documents and spreadsheets, I would like to do the same with any downloaded file, for example:

https://docs.google.com/file/d/0B-FYu_D7D7x4REdtRVEzVH0eU0/edit

In short, I wanted something like this:

 DriveApp.getFileByUrl(url).makeCopy(); 

Does anyone know if this is possible?

Any safe solution to extract the file id from the file url is also suitable for me.

thanks

+26
source share
6 answers

DriveApp is really missing getFileByUrl (as well as the folder for that matter). You might want to open a request for improvement in the application script tracker .

But what I do in my scripts (since these openByUrl functions openByUrl somewhat new) is to get the identifier using regular expressions. Like this.

 function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); } 

This regular expression works for any Google URL I tried: drive URL for folders and files, Fusion spreadsheets, spreadsheets, documents, presentations, etc. It just searches for everything in a string that is β€œsimilar” to a Google key. That is, any sufficiently large string containing only (Google key) valid characters.

Furthermore, it works even if it gets the identifier directly, not the URL. This is useful when you request a link from a user, as some may insert an identifier instead of a URL, and it still works.

--edit

There are some other answers and comments that relate to some extreme cases that I have never encountered, but may happen, for example, an attempt to get the folder ID by the URL of the subfolder, or when you have a G-Suite domain 25+ characters long In these cases, you can use a more strict regular expression.

Having briefly reviewed the suggestions below, I recommend the following /[-\w]{25,}$/ , since it is still very simple and should take these cases into account.

+57
source

The URL is similar to this, and the file identifier is present in this template "/ d / XXXXXXXX /" for almost all GoogleDrive / Docs links:
https://drive.google.com/file/d/0B3tB9BU9FRnpcTJmS2FoaktsQzA/view

Using the function below, we can get '/ d / fileid /' and then truncate '/ d /' from the beginning and '/' from the end.

 public static string getIdFromUrl(string url) { Regex r = new Regex(@"\/d\/(.+)\/", RegexOptions.IgnoreCase); Match m = r.Match(url); return m.ToString().TrimStart('/', 'd').Trim('/'); } 
+3
source

I don’t have enough reputation to comment on the accepted answer, but the accepted answer from Henrique G. Abreu fails when the drive URL contains the domain name and the domain name exceeds 25 characters (just figured it out the hard way :)

Otherwise, he was very reliable, and I think that he is the most elegant and reliable among those presented here.

So, expanding the accepted answer, the next regular expression will receive the last occurrence of a string of characters or hyphens from words with a length of at least 25 characters, which is immediately preceded by a character that is not a character without words or a hyphen. and perhaps it’s followed by the same type of character and any other garbage that may appear at the end:

 /.*[^-\w]([-\w]{25,})[^-\w]?.*/ 

This LOSES the characteristic of the accepted answer that it will work only after the identifier is transmitted, however this is not the use case that I need. It works for all the different types of URLs of disks, documents, sheets for both documents and folders that I tested.

+2
source

There are several URL extensions not listed above that may contain identifiers.

https://drive.google.com/drive/folders/ as well as https://drive.google.com/open?id= as well as https://drive.google.com/a/domain.edu.vn/ folderview? id =

I thought I would add my solution based on this idea and consider the above two extensions, as well as those that use / d /

 function getIdFrom(url) { var id = ""; var parts = url.split(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/); if (url.indexOf('?id=') >= 0){ id = (parts[6].split("=")[1]).replace("&usp",""); return id; } else { id = parts[5].split("/"); //Using sort to get the id as it is the longest element. var sortArr = id.sort(function(a,b){return b.length - a.length}); id = sortArr[0]; return id; } } 
+1
source

I just wanted to add a function that I created based on the two given answers, because none of them was what I was looking for.

 function templateIdFrom(url) { var parts = url.match(/\/d\/(.+)\//); if (parts == null || parts.length < 2) { return url; } else { return parts[1]; } } 

This gets the part after /d/ and until the next / , since the document URLs always contain their identifiers. If no match is found for this, we simply return the original parameter, which is considered an identifier.

0
source

The openByUrl method openByUrl now available in the Google Apps script.

See reference documents here for sheets , here for documents , here for slides and here for forms .

Because you wrote:

I want to get the ID of the document to create a copy in Google Drive

... I suppose you do not need an identity card as such. Having received the sheet / document / slide / form by URL, you can make a copy of it.

0
source

Source: https://habr.com/ru/post/1439343/


All Articles