Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I slice strings in Google Apps Script like in Python?

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);
}
like image 657
NonCreature0714 Avatar asked Dec 05 '25 13:12

NonCreature0714


1 Answers

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
like image 104
Alan Wells Avatar answered Dec 07 '25 16:12

Alan Wells