Get file/folder ID from url
Snippet
- See full code
- Leave a comment
- Create script from the snippet *See how to use scrviz for clone Apps Script project
/**
* Gets ID from URL
*
* @param {string} url The file url
* @returns {string} The file id
*/
function getIdFromUrl(url) {
const match = url.match(/[\w-_]{15,}/);
return match ? match[0] : undefined;
}
Run it
run.js/**
* This code runs the snippet
*/
function run() {
let url =
'https://docs.google.com/spreadsheets/d/19GRd3EarV_SM3Y8MYdpWvQNYZVZgLZih4EO4gX_JSko/edit#gid=1702180728';
console.log(getIdFromUrl(url));
url =
'https://drive.google.com/drive/folders/1nUB4UDrCNSbNmjSXy2H5DNz09s1LDEIb';
console.log(getIdFromUrl(url));
}
Test
test.jsInfo! You need enable
Drive
advanced service manually
/**
*
*/
function runTest() {
let passed = true;
const maxItems = 6000;
const items = [];
let fileList;
do {
fileList = Drive.Files.list({
maxResults: 1000,
pageToken: fileList ? fileList.nextPageToken : '',
});
items.push(...fileList.items);
console.info(items.length, fileList.nextPageToken);
} while (fileList.nextPageToken && items.length < maxItems);
items
.reduce(
(p, item) => (
p.push(
...['alternateLink', 'downloadUrl', 'exportLinks'].reduce(
(r, key) => (
typeof item[key] === 'string'
? r.push({
url: item[key],
id: item.id,
})
: typeof item[key] === 'object'
? r.push(
...Object.keys(item[key]).map((elk) => ({
url: item[key][elk],
id: item.id,
}))
)
: '',
r
),
[]
)
),
p
),
[]
)
.forEach((entry, i) => {
const test = getIdFromUrl(entry.url) === entry.id;
if (test == undefined) {
passed = false;
console.warn(i, entry.url, entry.id, getIdFromUrl(entry.url));
}
});
if (passed) console.log('Test is passed', items.length);
}