I'm new to Google Sheets and wondering how to tell GS to insert line breaks in a cell with text if there are some one or two letter before the text.
For instance, I have a cell like this:
I want to tell the script to create one paragraph for each choice:
It this case, the code must understand that the line breaks has to be before the pattern "[a,b,c,d, …]."
Important: each paragraph has to be in the same cell. Plus, on the spreadsheet there will be many cells (in the same column) so the code has to iterate the process for each cell.
Best Answer
This script will do the trick:
To set it up:
To use it:
Explanation and How to learn this stuff
The first part,
function InsertLineBreaksInString(str)
, processes a string by replacing some spaces with newline characters. If the argument is a string, it uses a "regular expression" to look for the pattern SPACE LETTER PERIOD and replace it with NEWLINE LETTER PERIOD. Regular expressions are handy for lots of string-processing work.This is a matter of JavaScript programming and regular expressions. There are many tutorials on these topics including Khan Academy classes, Codecademy classes, and more. You can experiment right in your browser's JavaScript Console and in online interactive tutorials like Learn JavaScript.
The second part,
function InsertLineBreaksInCells(range)
, uses the first function to process all the cell values in a spreadsheet range. See Google's Quickstart: Macros, Menus, and Custom Functions and Spreadsheet Service reference. Within Google Sheets, you can invoke the menu command Tools > Script Editor... to get to the script editor, and from there to the Help info.The third part,
function InsertLineBreaks()
, get the currently selected range in the current sheet, and calls the second function. See the same documentation for this.The last part,
function onOpen()
, adds a menu to the Google Sheet so you can invoke your script. This is documented in the Base Service part of the Apps Script reference, with examples, and there's also an example in the Quickstart mentioned above.