Ton
Ton

Reputation: 9736

How to replace all characters in a string using Google Scripts?

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

Answers (1)

Tanaike
Tanaike

Reputation: 201358

  • 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:

Upvotes: 1

Related Questions