I'm trying to make a Google Sheet that opens to an assigned sheet automatically for a large team using their gmail addresses when accessing it. How do I slice a string in Apps Scripts? The "email.slice" on line three is just something I made up as a place holder.
function onOpen() {
var email = Session.getActiveUser().getEmail();
var username = email.slice[0:-9];
var ss= SpreadsheetApp.openById(username);
SpreadsheetApp.setActiveSpreadsheet(ss);
}
The slice method returns part of the string. You could return all of it, but there's no point in that. There are two parameters, one is optional, the start and end parameters. Start comes first, end is second, and end is optional. If the end parameter is not used, the method automatically goes to the end of the string.
Apps Script uses JavaScript, so any JavaScript reference material that you want to use will give you the answers for almost everything related to basic programming.
In your case, you need to combine slice with indexOf().
var username = email.slice(0, email.indexOf("@"));
Logger.log('username is: ' + username); //VIEW, LOGS to see print out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With