The String object's concat() method
The concat()
method of the String object in Google Apps Script allows you to combine two or more strings into a single string. It is a useful function to have in your toolkit when working with strings in Google Apps Script.
In this tutorial, we will go over three examples of how to use the concat()
function in Google Apps Script, as well as the syntax of the function.
Syntax
The syntax for the concat()
function is as follows:
string.concat(string1[, string2[, ...[, stringX]]])
Here, string
is the original string, and string1
, string2
, etc. are the strings that you want to concatenate to the original string. You can include as many strings as you want, separated by commas.
Examples
Now, let's go over some examples of how to use the concat()
function in Google Apps Script.
Example 1: Concatenating Two Strings
The most basic use of the concat()
function is to combine two strings into a single string. Here is an example of how to do this:
function concatTwoStrings() {
var str1 = "Hello";
var str2 = "World";
var combined = str1.concat(str2);
Logger.log(combined); // Outputs "HelloWorld"
}
Example 2: Concatenating a String and an Object That Isn't a String
The concat()
function can also be used to concatenate a string with an object that isn't a string. In this case, the concat()
function will automatically convert the object to a string before concatenating it. Here is an example of how to do this:
function concatStringAndObject() {
var str1 = "The value of x is: ";
var x = 10;
var combined = str1.concat(x);
Logger.log(combined); // Outputs "The value of x is: 10"
}
Example 3: Concatenating Multiple Strings Where Some of the Strings Are Just Spaces
You can also use the concat()
function to concatenate multiple strings, including strings that are just spaces. This can be useful for adding spacing or formatting to your strings.
Here is an example of how to do this:
function concatMultipleStrings() {
var str1 = "Hello";
var space = " ";
var str2 = "World";
var combined = str1.concat(space, str2);
Logger.log(combined); // Outputs "Hello World"
}
I hope these examples have given you a better understanding of how to use the concat()
function in Google Apps Script. Remember, the concat()
method of the String object is a simple yet powerful tool that can be used to combine two or more strings into a single string.