Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace text in Google Spreadsheet using App Scripts?

Tags:

I tried to get the value of a range and than remove all points from the cell.

var FILE = SpreadsheetApp.openById("xyz");
var CONTENT = FILE.getSheetByName("Sheet1");
var A1 = CONTENT.getRange("I17").getValue();
A1. replace(".", "");

It gives me that can't find the replace function. Is there any function in Google Apps Script that allows me to replace the string?

like image 706
user2103505 Avatar asked Nov 09 '13 15:11

user2103505


People also ask

How do I change text in a Google script?

On your computer, open a document or presentation in Google Docs or Google Slides. Find and replace. Next to "Find," type the word you want to find. If you want to replace the word, enter the new word next to "Replace with."

How do I automatically replace text in Google Sheets?

To use REPLACE in Google Sheets, you simply need to type =REPLACE( into the cell where you want to perform the replacement, and then input the text you want to replace, the text you want to replace it with, and the number of times you want it to occur.

How do I add data to a Google spreadsheet using an app script?

The code uses the appendRow() method of the Sheet object to write a single row of data to the spreadsheet. To append a row, pass an array of values (corresponding to the columns) to the appendRow() method. For example, the code below appends a row containing two values: First name and Last name.


2 Answers

If this is an exact copy of your script then you have a space in-between A1. and replace but I assume it is not.

@SergeInsas is right the content needs to be a string for the replace() function to work, so if your trying to replace the . in a decimal number then you can use the toString() method first like below.

var FILE = SpreadsheetApp.openById("xyz");
var CONTENT = FILE.getSheetByName("Sheet1");
var A1 = CONTENT.getRange("I17").getValue();
var A1String = A1.toString().replace(".", "");

Or you can multiply the number to get rid of the decimal but this will depend on how many decimal places you have :)

like image 57
dev Avatar answered Sep 17 '22 13:09

dev


There is a more powerful, and simpler, method available: TextFinder.

The accepted answer to this question requires an additional step to post the replaced string back to the cell.

The TextFinder method does not need you to write the data back to the cell.

And if you want to search multiple cells, then this method saves you the iterations.

  var FILE = SpreadsheetApp.openById("xyz");
  var CONTENT = FILE.getSheetByName("Sheet1");
  var A1 = CONTENT.getRange("I17");
  A1.createTextFinder(".").replaceAllWith("");

I haven't tested it on a large data set but I suspect this would be quite quick.


Edit: I wrote a short tutorial on this.

like image 42
ADW Avatar answered Sep 19 '22 13:09

ADW