NonCreature0714
NonCreature0714

Reputation: 6024

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);
}

Upvotes: 2

Views: 34246

Answers (4)

Jonas_Z
Jonas_Z

Reputation: 11

It seems that the Splice function was reserved for Arrays and there is some issues applying it on Strings.

I have just created a small additional function that converts a String into an Array, makes the splice and then converts it back into a String:

function stringSplice(string,start,numElementsToDelete)
{
  var arr = [];
  var i;
  for(i = 0; i<string.length; i++) arr[i] = string[i];
  arr = arr.splice(start,numElementsToDelete)
  string = "";
  for(i = 0; i<arr.length; i++) string += arr[i];
  return string;
}

Then it works like a regular splice on Strings:

stringSplice("New_String",0,3);

Output: New

Upvotes: 1

Barry O&#39;Kane
Barry O&#39;Kane

Reputation: 1187

Substring will work as well

var username = email.substring(0, email.indexOf("@"));

Upvotes: 3

NonCreature0714
NonCreature0714

Reputation: 6024

Here is what I ended up doing:

function onOpen() {
    var email = Session.getActiveUser().getEmail();
    var ldap = email.slice(0,-11);
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(ldap));
    }

Worked well.

Upvotes: 1

Alan Wells
Alan Wells

Reputation: 31310

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

Upvotes: 5

Related Questions