Reputation: 9736
I am trying to replace specific characters in a Google Sheet cell using this code:
var sValue = data[0][0];
sValue = sValue .replace(" ", "");
var cell = sheet.getRange(1, 1);
cell.setValue(sValue);
If my text is "this is a test" I want to have "thisisatest" but the result is "thisis a test" Only first character is replaced. How can I replace them all?
Upvotes: 1
Views: 3508
Reputation: 201358
this is a test
to thisisatest
by replacing " "
to ""
.
this is a test
is in a cell on Google Spreadsheet.Here, I would like to propose to use TextFinder for your situation because of the following reasons.
getValues
and put by setValue
. When TextFinder is used, the search and replace process is run in the internal server. By this, the cost can be reduced.From your script, it supposes the situation that the value of this is a test
in the cell "A1" is converted to thisisatest
.
const sheetName = "Sheet1";
SpreadsheetApp
.getActiveSpreadsheet()
.getSheetByName(sheetName)
.getRange(1, 1)
.createTextFinder(" ")
.replaceAllWith("");
getRange(1, 1)
is removed like SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).createTextFinder(" ").replaceAllWith("");
, " "
in all cells in the sheet is replaced with ""
.Upvotes: 1