Home > Enterprise >  Removing characters from a range using regex in Google App Script
Removing characters from a range using regex in Google App Script

Time:08-09

I am trying to remove all non-digit characters from an extracted range in Google App Script.
For example, using the code snippet below, I am able to remove all "A" character from all cells within the range.

var range = sheet.getRange(1, 18, sheet.getLastRow(), 1);
range.createTextFinder("A").replaceAllWith("");

Now, instead of calling x instances of the .createTextFinder(n).replaceAllWith(""); function, I would like to use regex.
In particular, the '\D' expression would match all non-digit characters, I could then replace them with "".
The problem is I have no idea how to apply regex expressions to an entire range !
So far I'm assuming it's going to be something similar to the pseudo code below :

var range = sheet.getRange(1, 18, sheet.getLastRow(), 1);
var rangeValues = range.getValues();
rangeValues.forEach(//Somehow apply regex here)

How would you peole tackle this problem ?

CodePudding user response:

TextFinder accepts regular expressions:

range.createTextFinder(String.raw`\D`) /*https://stackoverflow.com/a/55793086*/
    .useRegularExpression(true)
    .replaceAllWith("");
  • Related