Home > OS >  Use JavaScript to get Google Sheet ID from URL
Use JavaScript to get Google Sheet ID from URL

Time:12-07

I'm currently using an input that parses a Google Sheet ID and inserts into code.

let sheetIdInput = document.getElementById('sheetidinput');

let id = sheetIdInput.value;

I want users to be able to paste the entire Google Sheet URL into this input sheetidinput and it to only use the Sheet ID from the URL.

Example Google Sheet URL is

https://docs.google.com/spreadsheets/d/132SaKuLRdHcwEKhhQVOKd2_3j30nFvQbTgplh4nPZOg/edit#gid=0

The Sheet ID is between .../d/ and /edit... in this case 132SaKuLRdHcwEKhhQVOKd2_3j30nFvQbTgplh4nPZOg

This pattern repeats itself in all Google Sheet URLS. Any help would be greatly appreciated.

CodePudding user response:

You could use regex to do it :

let url = "https://docs.google.com/spreadsheets/d/132SaKuLRdHcwEKhhQVOKd2_3j30nFvQbTgplh4nPZOg/edit#gid=0";
let capturedId = url.match(/\/d\/(. )\//)

console.log(capturedId[1])
// prints : 132SaKuLRdHcwEKhhQVOKd2_3j30nFvQbTgplh4nPZOg 

CodePudding user response:

You can use a regex:

var re = /.*\/d\/(.*)\/edit.*/;
var url = "https://docs.google.com/spreadsheets/d/132SaKuLRdHcwEKhhQVOKd2_3j30nFvQbTgplh4nPZOg/edit#gid=0
";
var match = url.match(re);
var id = match[1]
//Use id
}
  • Related