Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-apps

Q: Google Sheet Script to alter columns so in front of numbers its adding an hashtag


im looking for help/script where it replace/append a number (1-999) within several colums (example: A10:D200) with an additional hashtag (#1 - #999).

Example Before:

A B C D
123 456 31 5
6 888 123 9
92 55 3 791
11 2 456 712

How it should look:

A B C D
#123 #456 #31 #5
#6 #888 #123 #9
#92 #55 #3 #791
#11 #2 #456 #712

and so on

function onEdit() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Stewarding - Imola Q")
      var lastRow = sheet.getLastRow()
      var lastColumn = sheet.getLastColumn()
      var range = sheet.getRange(10, 1, lastRow, 4)
      var to_replace = [0-9];
      var replace_with = "#";
      var data  = range.getValues();
    
        var oldValue="";
        var newValue="";
        var cellsChanged = 0;
    
        for (var r=0; r<data.length; r++) {
          for (var i=0; i<data[r].length; i++) {
            oldValue = data[r][i];
            newValue = data[r][i].replace(to_replace, replace_with +oldValue);
            if (oldValue!=newValue)
            {
              cellsChanged++;
              data[r][i] = newValue;
            }
          }
        }
        range.setValues(data);
        //Logger.log(data);
    }

thanks for any help in advance


Solution

  • Alternatively it can be done this way:

    function myFunction() {
      const sheet = SpreadsheetApp.getActiveSheet(); // your sheet
      const range = sheet.getRange('A10:D200'); // your range
    
      // find all digits and put # before
      range.createTextFinder('(\\d+)').useRegularExpression(true).replaceAllWith('#$1');
    }
    

    To prevent double ## after a rerun of the scipt the last line could be like this:

    range.createTextFinder('^\\D*(\\d+)').useRegularExpression(true).replaceAllWith('#$1');
    

    It will change any number of any non-digits characters before digits with one # at the start of every cell of the range.