Home > Enterprise >  Google Apps Script Find and Replace with Quantifier
Google Apps Script Find and Replace with Quantifier

Time:11-04

On my sheet I have a bunch of cells that contain text, then the letters "TRT" and then a bunch of random numbers.

I want to remove TRT and everything after it.

Meaning:

"Test File TRT 111134" should become "Test File"

I know I can do this easily with MID, or LEFT, but I need a way to run this regular across a range using apps script.

I tried to tweak something like this to include the quantifier, but no luck:

function replacetool() {
   var FILE = SpreadsheetApp.openById("1n7vb6uyo6W9NX7EDWZvcbn-SptMDorgwvImZcPSdyR0");
  var CONTENT = FILE.getSheetByName("Sheet1");
  var A1 = CONTENT.getRange(1,1,100,100);
  A1.createTextFinder("TRT"& "#.*").replaceAllWith("");

}

Any thoughts?

CodePudding user response:

This works for me

function replacetool() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet1");
  const rg = sh.getDataRange();
  rg.createTextFinder("TRT.*").useRegularExpression(true).replaceAllWith("");
}

Before:

A
Test File TRT 111134
Test File TRT 111134
Test File TRT 111134
Test File TRT 111134

After:

A
Test File
Test File
Test File
Test File
  • Related