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?

3
  • Does this answer your question? How to replace all occurrences of a string? Commented Apr 16, 2020 at 15:34
  • Which answer would you recommend for the OPs case as there 63 answers? Commented Apr 16, 2020 at 15:42
  • @Cooper The fastest and easiest stackoverflow.com/a/59503209 function C here: Regex based one. Commented Apr 16, 2020 at 17:27

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.