How to Split String Using Apps Script in Google Sheets

We often require to split appended values from a cell. For example, we can separate the first and last names from a list of full names, divide URLs and email extensions or extract known values from a string by performing the split operation. There is a function and a feature that can execute the split operation. However, in this article, I’ll demonstrate how you can use the Google Apps Script to split a string in Google Sheets. We’ll discuss 3 ideal examples of splitting a string and endow the script required for executing a split operation. The following image contains an overview of the result attained after implementing the required script.

An overview of the required output


A Sample of Practice Spreadsheet

You can copy our practice spreadsheets by clicking on the following link. The spreadsheet contains an overview of the datasheet and an outline of the demonstrated examples to split any string using a script in Google Sheets.


3 Ideal Examples to Split String Using Apps Script in Google Sheets

First, let’s look at the dataset we’ll use for most of this article. The dataset contains a list of names that we want to split into two different cells. Now, let’s start.

Dataset used to split a string using script in Google Sheets


1. Splitting Strings Containing Equal Number of Parts

First, we’ll consider splitting strings that contain an equal number of parts. Every full name in our dataset contains only two parts (first name and last name). Now, let’s write a script and implement it to split the full names into first names and last names. Basically, we’ll create a function using Apps Script to split the strings.

Steps:

  • From the worksheet where you want to implement the script, go to the Extensions ribbon and select Apps Script from the appeared options.

Selecting Apps Script from Extensions Ribbon

  • At this point, you will have a new window like the following in your browser where you can write the script.

New Window for Inserting Script in Google Sheets

  • Now, rename the project and file.
  • Afterward, insert the following script-
function splitDataEqual() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var last_row = ss.getLastRow();
  var last_col = ss.getLastColumn();
  for (var i=5; i<=last_row;i++){
    var fullName = ss.getRange(i,2).getValue();
    var partName = fullName.split(" ");
    for(var j=3;j<=last_col;j++){
      var req_info = partName[j-3];
      ss.getRange(i,j).setValue(req_info);
    }
  }
}

The Script used to Split a String containing an equal number of parts

  • Then, Save and Run the project to execute the split operation. Provide all the required accesses for authorization.

Save and Run the file for Execution of the Script

  • Now, as soon as the file execution is completed, return to the Google Sheets window to check the results.
  • As we can see, the full names have been split into first names and last names for the range.

Final output after implementing the script

Read More: How to Split Cells to Get Last Value in Google Sheets (4 Methods)


2. Separating Strings Containing Unequal Number of Parts

Now, let’s consider a little complex scenario. In the dataset below we have a list of full names where the strings don’t have an equal number of parts. Some strings contain first, middle, and last names. Whereas, some strings also have extensions to their first, middle, and last names. On the contrary, some strings consist of only first and last names. So, how can we perform a split operation for this dataset? Keep reading to learn how.

Dataset for Demonstrating the Split operation for a string containing unequal number of parts using script in Google Sheets

Steps:

  • First, open the Apps Script window from the Extensions ribbon.
  • Since a script is already present, click on the Add a File icon first and then select Script from the two options to open a new file.

Inserting a new Script File from Add a File icon

  • After a new file opens, rename the file and insert the following script-
function splitDataUnequal() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var last_row = ss.getLastRow();
  var last_col = ss.getLastColumn();
  var nameparts =[];
  var req_info;
  for (var i=5; i<=last_row;i++){
    var fullName = ss.getRange(i,2).getValue();
    var partName = fullName.split(" ");
    if (partName.length >= 3){
      [nameparts[0],nameparts[1],...nameparts[2]] =partName;
      for(var j=3;j<=last_col;j++){
        if(j<last_col){
          req_info = nameparts[j-3];
        }
        if (j==last_col){
          req_info = nameparts[j-3].join(" ");

        }
        ss.getRange(i,j).setValue(req_info);
      }
    }
    else{
      nameparts[0] = partName[0]
      nameparts[1] = "-"
      nameparts[2] =partName[1];
      for (var k=3;k<=last_col;k++){
        req_info = nameparts[k-3];
        ss.getRange(i,k).setValue(req_info);
      }
      }
    }
  }

Inserting the Script for performing Split of a String containing an unequal number of parts in Google Sheets

  • Now, Save and Run the file. We authorized the permissions in the previous example. Hence, we don’t require authorization again in this example.

Run and Save the file to execute the script

  • After the file execution is completed, return to the Google Sheets window to check the output. We have got the following output after the execution of the script.

Final Output after Execution of the required Script

  • Here, the names containing first, middle, and last names have been split into the required cells.
  • For the names which contain an extension, the extension is appended with the last name.
  • And for the names that don’t consist of a middle name, we have put a hyphen (“”) symbol to depict its absence.

Read More: How to Split a Cell in Google Sheets (9 Quick Methods)


3. Dividing Strings Around Multiple Delimiters

The dataset for the previous two examples contained only one delimiter. So you may wonder how can we split strings that contain multiple delimiters. Let’s have a look at the following dataset. Every cell of Column B contains the first name, last name, profession, and accommodation region of a person separated by space (“ ”), hyphen (“-”), and comma (“,”) delimiters. Now let’s write a script to execute the split operation here.

Dataset for demonstrating how to split a string containing multiple delimiters using script in Google Sheets

Steps:

function splitDataMultipleDelimiter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var last_row = ss.getLastRow();
  var last_col = ss.getLastColumn();
  var search = ["-",","];
  var r = [" "];
  ss.getDataRange().createTextFinder(search.join("|")).
  useRegularExpression(true).replaceAllWith(r);
    for (var i=5; i<=last_row;i++){
      var fullName = ss.getRange(i,2).getValue();
      var partName = fullName.split(" ");
      for(var j=3;j<=last_col;j++){
        var req_info = partName[j-3];
        ss.getRange(i,j).setValue(req_info);
      }
  }
}

Inserting a Script to Split Strings with Multiple Delimiters

  • At this point, Save and Run the file.

Save and Run the File to Execute the Script

  • After the file execution is complete, the dataset now looks like the following.
  • As we can see, the string is split into the required cells. However, the source strings that were split have also changed. Instead of multiple delimiters, only one delimiter is present now. This is because the script tokens for split operation can deal with only one delimiter. Hence, we replaced every other delimiter with a single delimiter.

Final Output after the Execution of the String

Read More: How to Split Cell by Comma in Google Sheets (2 Easy Methods)


Alternatives of Using Apps Script to Split String in Google Sheets

In the previous section, we used scripts to split strings in Google Sheets. There are a couple of functions and features to perform a similar operation without a script. Keep reading to learn about the implementation of these alternatives.

1. Applying Split Text to Columns Feature

The first alternative we want to demonstrate is the Split Text to Columns feature. The Split Text to Columns feature can split strings of a range around a delimiter. Follow the simple steps below to execute this feature.

Steps:

  • Firstly, select the range B5:B10 and copy it by using the keyboard shortcut CTRL+C.

Copying the Required Range to Perform Split Operation

  • Now, select Cell C5 and use the keyboard shortcut CTRL+V to paste the copied range. At this time, the clipboard for paste formatting will be visible. Click on the clipboard menu.

Applying paste using Keyboard Shortcut for the copied range

  • As soon as you click on the clipboard menu, a list of options will appear. Select the Split Text to Columns feature from the list.

Selecting Split Text to Column feature from Clipboard Menu

  • Another way to select the Split Text to Columns feature is to select the C5:C10 range first and then go to the Data ribbon to select the Split Text to Columns feature next.

An alternative way to select the Split Text to Columns Command

  • After selecting the Split Text to Column feature, a clipboard like the following will appear where you can choose the separator around which the split operation will be executed.

Separator Clipboard Generated after Sleecting Split Text to Columns Feature

  • Click on the Separator clipboard to generate a list of separators and select Space from the list. You may choose the separator you require. You can also insert a custom separator if it isn’t available in the appeared list.

Selecting Space as Required Separator

  • As soon as you select the Space option as the separator for the Split Text to Columns command, the copied values will be split into required columns.

The final output after applying Split Text to Columns Feature

Read More: How to Split Text to Columns Using Formula in Google Sheets


2. Employing SPLIT Function

Another alternative to implementing a script for splitting strings is to employ the SPLIT function. It is an exclusive function for Google Sheets and allocates values in adjacent cells of a row around a delimiter.

Steps:

  • Firstly, activate Cell C5 by double-clicking on it.
  • Then, type in the following formula-
=SPLIT(B5," ","")
  • Afterward, press the Enter key to get the required output.

Employing SPLIT function to Split a String as an alternative to Script in Google Sheets

  • Now, select Cell C5 again and then hover the mouse pointer above the bottom-right corner of the selected cell.
  • The Fill Handle icon will be visible at this time.
  • Finally, use the Fill Handle icon to copy the formula to other cells of Column C.

Using Fill handle tool

  • The final output looks like the following after using the Fill Handle tool.

Final Output after Applying the SPLIT function

Read More: How to Use QUERY with SPLIT Function in Google Sheets


3. Combining SPLIT and REGEXREPLACE Functions

In the 3rd example of the previous section, we performed a split operation for strings with multiple delimiters by implementing a script. The source range was also modified after the implementation of the script. If you want to keep the source range unchanged, you can combine the SPLIT and REGEXREPLACE functions.

Steps:

  • Firstly, select Cell D5.
  • Afterward, insert the following formula-
=SPLIT(REGEXREPLACE(B5,"-|,"," ")," ","")
  • Later, get the required output by pressing the Enter key.
  • Finally, Finally, use the Fill Handle icon to copy the formula to other cells of Column D.

Combining SPLIT and REGEXREPLACE Functions to Split a String with Multiple Delimiters in Google Sheets

Formula Breakdown

  • REGEXREPLACE(B5,”-|,”,” “)

The SPLIT function can’t actually divide texts based on multiple delimiters. Hence, we have used the REGEXREPLACE function for substituting every other delimiter for a single delimiter. Here, we have substituted every other delimiter with spaces (“ ”).

  • SPLIT(REGEXREPLACE(B5,”-|,”,” “),” “,””)

And now, the SPLIT function divides the space-separated values into adjacent cells of a row.

  • The final output looks like the following after using the Fill Handle tool.

Combining SPLIT and REGEXREPLACE Functions

Read More: How to Split String into Array in Google Sheets (3 Easy Methods)


Things to Be Considered

  • You have to be in the sheet where you can the script to be implemented to make it the active sheet for your script. Otherwise, you need to get your sheet by name for the proper execution of your script.

Conclusion

This concludes our article to learn how to split a string using Apps Script in Google Sheets. I hope the demonstrated examples were ideal for your requirements. Feel free to leave your thoughts on the article in the comment box. Visit our website OfficeWheel.com for more helpful articles.


Related Articles

Seemanto Saha

Seemanto Saha

Hello, I am Seemanto Saha, and working as a Technical Writer and Content Creator at OfficeWheel.com. I completed my B.Sc. in Industrial and Production Engineering from Bangladesh University of Engineering and Technology. Being an enthusiast for solving analytical problems, I aim to leverage my research and analytical skills to create better content for everyone.

We will be happy to hear your thoughts

Leave a reply

OfficeWheel
Logo