1

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?

TheMaster
  • 45,448
  • 6
  • 62
  • 85
Ton
  • 9,235
  • 15
  • 59
  • 103
  • Does this answer your question? [How to replace all occurrences of a string?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string) – TheMaster Apr 16 '20 at 15:34
  • Which answer would you recommend for the OPs case as there 63 answers? – Cooper Apr 16 '20 at 15:42
  • @Cooper The fastest and easiest https://stackoverflow.com/a/59503209/ function C here: Regex based one. – TheMaster Apr 16 '20 at 17:27

1 Answers1

1
  • You want to convert this is a test to thisisatest by replacing " " to "".
    • The value of this is a test is in a cell on Google Spreadsheet.
  • You want to achieve this using Google Apps Script.

Here, I would like to propose to use TextFinder for your situation because of the following reasons.

  1. In your situation, Google Spreadsheet is used.
  2. In your script, the values are retrieved by 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.
  3. TextFinder can be used for a cell, a range, a sheet and all sheets in Spreadsheet by the simple script.

Sample script:

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("");

Note:

  • For example, in above script, when getRange(1, 1) is removed like SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName).createTextFinder(" ").replaceAllWith("");, " " in all cells in the sheet is replaced with "".

Reference:

halfer
  • 19,824
  • 17
  • 99
  • 186
Tanaike
  • 181,128
  • 11
  • 97
  • 165