Easiest way to get file ID from URL on Google Apps Script

DriveApp is indeed missing a getFileByUrl (and also folder for that matter). You may want to open an enhancement request on Apps Script issue tracker.

But what I do on my scripts (since these openByUrl functions are somewhat new), is to get the id using a regex. Like this.

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

This regex works for any google url I’ve tried: Drive url for folders and files, Fusion Tables, Spreadsheets, Docs, Presentations, etc. It just looks for anything in a string that “looks like” a Google key. That is, any big enough string that has only (google key) valid characters in it.

Also, it works even if it receives the ID directly, instead of the URL. Which is useful when you’re asking the link from the user, as some may paste the id directly instead of the url and it still works.

–edit

There are some other answers and comments that address some edge cases that I never encountered myself but might happen, like trying to get a folder-id on a nested folder URL, or when you have G-Suite domain that is 25+ characters long. For those cases, you might want to use a more strict regex.

From a quick look at the suggestions below I recommend the following /[-\w]{25,}(?!.*[-\w]{25,})/ because it is still very simple and should address these cases.

Leave a Comment