Home > Software engineering >  Google Apps Script in Sheets to remove last character
Google Apps Script in Sheets to remove last character

Time:08-06

I wish to remove the last character of each row in a specific column, and unfortunately could not find any ways as to accomplish this.

Sample data looks as follows:

enter image description here

Thanks,

CodePudding user response:

Try

function removeLastCharacter() {
  const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  const rng = sh.getRange('A2:A'   sh.getLastRow())
  const data = rng.getValues()
  data.map(r => r[0] = r[0].substring(0, r[0].length - 1))
  rng.setValues(data)
}

or if you want to remove :

function removeLastCharacter() {
  const sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  const rng = sh.getRange('A2:A'   sh.getLastRow())
  const data = rng.getValues()
  data.map(r => r[0] = r[0].replace(/:/,""))
  rng.setValues(data)
}

CodePudding user response:

As another direction, how about using TextFinder as follows?

Sample script:

function myFunction() {
  const sheetName = "Sheet1"; // Please set the sheet name.

  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  sheet.getRange("A2:A"   sheet.getLastRow()).createTextFinder(".$").useRegularExpression(true).replaceAllWith("");
}
  • In this sample script, from your showing sample image, the last character of the cells "A2:A" is removed.
  • If you want to remove the specific character (:) at the last character, please modify .$ to :$.

Reference:

  • Related