The slice() method in Apps Scripts returns a section of a string based on the specified indexes. It takes two arguments – the start and end indexes of the slice. The start index is inclusive, and the end index is exclusive.
For example, if we have a string “Hello World!”, we can use the slice() method to extract a portion of it, like “World!”. We can do this by specifying the start index as 6 (which is the index of the “W” character) and the end index as 12 (which is the index of the “!” character).
var str = "San Francisco"; var city = str.slice(4, 12); Logger.log(city); // Output: Francisco
In this example, we use the slice() method to extract the word “Francisco” from the string “San Francisco”. The start index is 4 (which is the index of the space character) and the end index is 12 (which is the index of the “o” character).
var str = "Welcome to New York"; var location = str.slice(11); Logger.log(location); // Output: New York
In this example, we use the slice() method to extract the location “New York” from the string “Welcome to New York”. Since we only provide the start index as 11, the slice() method automatically extracts the substring starting from index 11 till the end of the string.
These are just a couple of examples of how to use the slice() method. It can be used in various scenarios where you need to extract a specific portion of a string.