Search code examples
javascriptgoogle-sheetsvariables

Javascript to remove text before point


I have a Google spreadsheet that receives new rows of data when a website form is submitted. I need to find the latest entry and remove a piece of text from a that row in column N.

The last cell with data, in column N contains an address with an unwanted piece of text at the beginning. Example:

"From: this address & Postcode: 123 Street address, town, city, zip code."

I need to remove "From: this address and Postcode: " from the text in the cell.

I have the js to find the last row of data and remove a piece of text, but it's removing everything AFTER "Postcode: " and I need it to remove everything BEFORE "Postcode: ", leaving everything after Postcode in the cell

function removeTags(){
  var column = 14
  var sh = SpreadsheetApp.getActive().getActiveSheet();
  var data = sh.getRange(1,column,sh.getLastRow(),1).getValues();
  for(var n in data){
    if(data[n][0]==''){continue};// if cell empty then continue
    var str = data[n][0].toString();
    data[n][0]= str.substring(0,str.indexOf("Postcode: "));//remove everything after Postcode: 
  }
  sh.getRange(1,column,sh.getLastRow(),1).setValues(data);// update sheet with new data
}

Can someone look at the script and tell me how to swap what is deleted?

I tried to remove some str. and other tweaks to try and fix it, but I'm new to js and don't fully understand the order of operations


Solution

  • You should get the substring from where "Postcode: " is found, and until the end. I modified that, and added an if statement to not do anything if it was already removed:

    function removeTags() {
      var column = 14
      var sh = SpreadsheetApp.getActive().getActiveSheet();
      var data = sh.getRange(1, column, sh.getLastRow(), 1).getValues();
      for (var n in data) {
        if (data[n][0] == '') { continue };// if cell empty then continue
        var str = data[n][0].toString();
        var location = str.indexOf("Postcode: ");
        if (location != -1) {
          data[n][0] = str.substring(location + 10, str.length - 1);//remove everything BEFORE Postcode: 
        }
      }
      sh.getRange(1, column, sh.getLastRow(), 1).setValues(data);// update sheet with new data
    }
    

    enter image description here