javascript 如何像在 Python 中一样在 Google Apps Script 中对字符串进行切片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28247207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:40:01  来源:igfitidea点击:

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

javascriptstringgoogle-apps-script

提问by NonCreature0714

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.

我正在尝试制作一个 Google 表格,该表格在访问它时使用他们的 gmail 地址自动为大型团队打开到指定的工作表。如何在 Apps 脚本中对字符串进行切片?第三行的“email.slice”只是我作为占位符编写的。

function onOpen() {
    var email = Session.getActiveUser().getEmail();
    var username = email.slice[0:-9];
    var ss= SpreadsheetApp.openById(username);
    SpreadsheetApp.setActiveSpreadsheet(ss);
}

回答by Alan Wells

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 startand endparameters. Startcomes first, endis second, and endis optional. If the endparameter is not used, the method automatically goes to the end of the string.

slice 方法返回字符串的一部分。你可以全部归还,但这没有意义。有两个参数,一个是可选的,开始结束参数。 开始在前,结束在后,结束是可选的。如果不使用end参数,该方法会自动转到字符串的末尾。

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.

Apps Script 使用 JavaScript,因此您想要使用的任何 JavaScript 参考资料都会为您提供与基本编程相关的几乎所有内容的答案。

In your case, you need to combine slice with indexOf().

在您的情况下,您需要将 slice 与indexOf().

var username = email.slice(0, email.indexOf("@"));
Logger.log('username is: ' + username); //VIEW, LOGS to see print out

回答by Barry O'Kane

Substring will work as well

子字符串也能工作

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

回答by NonCreature0714

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.

工作得很好。