Home > Net >  Google Sheets script – replace blank spaces
Google Sheets script – replace blank spaces

Time:02-11

I've got a script that's doing some onEdit formatting on a sheet of mine. All the rest is working well, and I wanted to include a line that deletes spaces from number values I'm importing. That last line is not working.

Any ideas what I'm missing here?

function onEdit(e) {
  var cell = e.range;
  var sh = e.source.getActiveSheet();  
  if(sh.getName() === "Trading Journal") {
    cell.setBackground('#fff');
    cell.setFontSize(10)
    cell.setFontFamily()
    cell.replace(/\s/g, "") 
}
}

https://docs.google.com/spreadsheets/d/1vFIiKIenzVWkrQ39Pg0ASQU9EoGe07CrTJfiR2NJ3RE/edit?usp=sharing

CodePudding user response:

Check if what you expect as a space is not a non-breaking space char(160), and replace \s by

cell.replace(/ /g,"")

in this formula, it is not a space but char(160)

Best way to use it is to copy/paste...

CodePudding user response:

Did a bit of research regarding this, and it seems that .replace() is a string method and therefore may not work with numbers. Reference

But if you only need to remove whitespaces from numbers, here is a simple solution:

function rSpaces() {
    var ss =  SpreadsheetApp.getActiveSpreadsheet();
    var cell = ss.getActiveCell();
    cell.trimWhitespace();
}

You can assign this on an onEdit trigger and check this documentation for any font modifications you want to add.

  • Related