The String object's split() method
The String object's split()
method divides a string into an array of substrings based on a specified delimiter and returns the array.
Prerequisites
This tutorial assumes that you're familiar with:
Syntaxstring.split([separator[, limit]])
Parametersseparator (optional):
Specifies the string or regular expression to use for splitting
If omitted, returns an array with the entire string as a single element
If empty string (''), splits the string into an array of individual characters
limit (optional):
string.split([separator[, limit]])
separator (optional):
Specifies the string or regular expression to use for splitting
If omitted, returns an array with the entire string as a single element
If empty string (''), splits the string into an array of individual characters
Integer specifying a limit on the number of splits to be found
The array will have no more than limit elements
Remaining text is not included in the array if limit is reached
Return value
Returns an array of strings, split at each point where the separator occurs in the string.
ExamplesExample 1: Basic string splitting
In the code below, the function splitEx1()
demonstrates basic ways to split strings.
function splitEx1() {
let str = "apple,banana,orange,grape";
// Split by comma
Logger.log(str.split(','));
// Split by empty string (into characters)
Logger.log("Hello".split(''));
// Split with no separator
Logger.log("Hello World".split());
}
Output
[apple, banana, orange, grape]
[H, e, l, l, o]
[Hello World]
Example 2: Using a limit parameter
In the code below, the function splitEx2()
shows how to limit the number of splits.
function splitEx2() {
let str = "one-two-three-four-five";
// Get first three items
Logger.log(str.split('-', 3));
// Get first two items
Logger.log(str.split('-', 2));
// Split CSV but keep last columns merged
let csvLine = "field1,field2,field3,field4,field5";
Logger.log(csvLine.split(',', 3));
}
Output
[one, two, three]
[one, two]
[field1, field2, field3]
Example 3: Using regular expressions
In the code below, the function splitEx3()
demonstrates splitting with regular expressions.
function splitEx3() {
// Split on multiple delimiters
let str1 = "apple,banana;orange|grape";
Logger.log(str1.split(/[,;|]/));
// Split on whitespace
let str2 = "Hello World\tApps\nScript";
Logger.log(str2.split(/\s+/));
// Split keeping delimiters using capture groups
let str3 = "apple+banana-orange";
Logger.log(str3.split(/([+-])/));
}
Output
[apple, banana, orange, grape]
[Hello, World, Apps, Script]
[apple, +, banana, -, orange]
Example 4: Common use cases
In the code below, the function splitEx4()
shows practical applications of split()
.
function splitEx4() {
// Parse CSV data
let csvRow = "John,Doe,johndoe@example.com,123-456-7890";
let [firstName, lastName, email, phone] = csvRow.split(',');
Logger.log(`Name: ${firstName} ${lastName}`);
// Format file path parts
let filePath = "/Users/username/documents/file.txt";
let pathParts = filePath.split('/');
Logger.log("Filename: " + pathParts[pathParts.length - 1]);
// Parse query string
let queryString = "name=John&age=30&city=NewYork";
let params = queryString.split('&').map(param => {
let [key, value] = param.split('=');
return `${key}: ${value}`;
});
Logger.log(params);
}
Output
Name: John Doe
Filename: file.txt
[name: John, age: 30, city: NewYork]
Common Use Cases
The split()
method is versatile and commonly used in many text processing scenarios. Here are typical applications:
CSV parsing: Split comma-separated data into individual fields for processing.
Name parsing: Separate full names into first and last names for standardization.
URL processing: Break down URLs into their component parts for analysis.
Text analysis: Split text into words or sentences for processing or counting.
Data cleaning: Split and reconstruct strings to remove unwanted characters.
Configuration parsing: Split configuration strings into key-value pairs.
Note
Here are some key characteristics to remember when using the split()
method:
The method includes empty elements in the resulting array if there are consecutive separators (e.g.,
"a,,b".split(',')
returns['a', '', 'b']
)When the separator isn't found in the string, split() returns an array with the entire original string as its only element (e.g.,
"hello".split('x')
returns['hello']
)While regular expressions make splitting more powerful by allowing complex pattern matching, they can also introduce unexpected results if not used carefully
Conclusion
In this tutorial, you learned how to use the split()
method to divide strings into arrays in Apps Script. This method is useful for text processing, data parsing, and string manipulation tasks. Whether you're working with simple comma-separated values or complex text patterns, split()
provides flexible ways to break down strings into manageable pieces. Remember that split()
returns a new array and doesn't modify the original string.