// Drive · Apps Script

Extract a Drive file ID from any share URL.

One regex function that pulls the file ID out of every Drive URL shape — /d/ID/, ?id=ID, and open?id= — without brittle string splitting.

I have a Google Drive share URL in a spreadsheet cell and I need the raw file ID so I can call DriveApp or the Drive API from Apps Script.

The script

copy · paste · trigger
driveFileId.gs
Apps Script
// driveFileId.gs — pull a Drive file ID from any share URL
// Handles: /d/<id>/, ?id=<id>, /open?id=<id>, /uc?id=<id>

function extractDriveFileId(url) {
  if (!url) return null;
  var pattern = /[?&\/](?:id=|d\/)([a-zA-Z0-9_-]{25,})/;
  var match = url.match(pattern);
  return match ? match[1] : null;
}

// Example: read URLs from column A, write IDs to column B
function fillFileIds() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var urls = sheet.getRange('A2:A').getValues();
  var ids = urls.map(function(row) {
    return [extractDriveFileId(row[0])];
  });
  sheet.getRange(2, 2, ids.length, 1).setValues(ids);
}

Need a variant? Gnaw writes a custom version from one sentence — fields, triggers, edge cases handled.

Walkthrough

Why Drive hands you three different URL shapes

Google Drive has never settled on a single URL format. Files opened from Drive UI look like `https://drive.google.com/file/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms/view`. Files shared via the old direct-download route look like `https://drive.google.com/uc?id=1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms`. Folders and some editor-created files (Docs, Sheets, Forms) use `https://docs.google.com/spreadsheets/d/<id>/edit` instead of the drive.google.com host. The ID itself is always the same 33-character base64url string — it is the URL shape around it that changes.

Splitting on '/' and grabbing a fixed index works until it doesn't. The moment someone pastes a folder URL or a Docs link instead of a Drive file link, your index is wrong and you get a path segment instead of an ID. The regex approach targets the ID by what precedes it — either the literal string `d/` or the query-parameter key `id=` — so the host, path depth, and trailing segments are irrelevant.

How the regex works

The pattern `/[?&\/](?:id=|d\/)([a-zA-Z0-9_-]{25,})/` reads in three pieces. The character class `[?&\/]` matches the character that always appears immediately before the ID token — a query-string delimiter (`?` or `&`) for the `id=` shape, or a path separator (`/`) for the `d/` shape. The non-capturing group `(?:id=|d\/)` then matches exactly one of the two key strings. The capturing group `([a-zA-Z0-9_-]{25,})` grabs everything that looks like a Drive ID: base64url characters, at least 25 of them.

The minimum-length guard of 25 prevents accidentally capturing a short path token. Real Drive IDs are 33 characters as of 2026, but Google has used shorter IDs for legacy files, so 25 is the right floor. The first time I hit a false-positive capture, it was because I had used `{10,}` and a query parameter value from a tracking redirect matched before the actual ID — raising the floor to 25 fixed it cleanly.

Wiring it into a Sheets column batch

The `fillFileIds` function is the practical use case: you have a column of Drive URLs (pasted from a shared folder listing or from a HYPERLINK formula) and you want the corresponding IDs next to them so you can pass them to `DriveApp.getFileById()` or build Drive API calls.

One thing worth knowing: `getRange('A2:A').getValues()` returns every row to the last row of the sheet's used range, but empty rows at the bottom still come back as empty strings, not nothing. The `extractDriveFileId` call handles that with the `if (!url) return null` guard — you get a null in those cells rather than an error. If you need to stop at the actual last row of data, replace `'A2:A'` with a range bounded by `sheet.getLastRow()`.

Want a custom version?

Describe your sheet and the rule you want. Gnaw writes the Apps Script — fields, triggers, edge cases — in one shot.

FAQ

4 questions
Does this work for Google Docs, Sheets, and Slides URLs, not just Drive file URLs?
Yes. Docs/Sheets/Slides URLs use the same /d/<id>/ shape — for example, `https://docs.google.com/spreadsheets/d/1BxiMVs0.../edit`. The regex matches on the path token `d/` regardless of the host, so it works across all Google editor URLs.
What if the URL is a Drive folder link?
Folder URLs use `/folders/<id>` rather than `/d/<id>/`, so the regex will not match them. If you need to handle folder links too, add `folders/` as a third alternative in the non-capturing group: `(?:id=|d\/|folders\/)`. The ID format is identical.
Can I use this as a custom function directly in a Sheets cell?
Add the `@customfunction` JSDoc tag above `extractDriveFileId` and it becomes callable as `=EXTRACTDRIVEFILEID(A2)` in the sheet. Remove the `fillFileIds` batch helper in that case — you will not need it. Custom functions cannot call most Apps Script services, but this function is pure string work so there is no service restriction to hit.
The function returns null for a URL I know is valid. What is wrong?
The most common cause is a URL that was auto-shortened (goo.gl or a corporate redirect) before it reached your script. The regex needs the actual drive.google.com or docs.google.com URL. Use UrlFetchApp.fetch(shortUrl, {followRedirects: true}) and read the final URL from the response headers before passing it to extractDriveFileId.
// one good script a week

Get a working Apps Script snippet in your inbox, weekly.