Home > Software engineering >  Google Apps Script Trim White Space at the beginning of a string for an entire column
Google Apps Script Trim White Space at the beginning of a string for an entire column

Time:06-08

Sample Spreadsheet Tab - Result

I want to remove spaces in front of the text in Col. B

None of the codes I tried seem to be working. I tried the replace method, then split & join. But it still leaves a blank space in front of the text.

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "Result";
  var sheet = ss.getSheetByName(sheetname);
  sheet.getRange('B2:B').activate();
  var ranges = sheet.getActiveRangeList().getRanges();
  for (var i = 0; i < ranges.length; i  ) {
    ranges[i].getValue().split(' ').join('');

I did numerous searches in stack and Google, but none of them seem to work. What am I doing wrong here?

CodePudding user response:

I don't see data in Tab 'Result' - Column B to test it out but if you're just trying to remove blank space from the beginning of the text in a range, you can try:

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetname = "Result";
  var sheet = ss.getSheetByName(sheetname);
  
  var lastRow = sheet.getLastRow();
  var range = sheet.getRange("B2:B" lastRow);
  range.trimWhitespace();

CodePudding user response:

try adding replaceAll(" ","") to you string ranges[i].getValue().replaceAll(" ","")

  • Related