I will answer my own question because what seemed to be a rather simple task took a good time of my day today.
function deleteRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var textToFind = "specific text";
var rowsToDelete = [];
var lastRow = sheet.getMaxRows();
var formulas = sheet.getRange("G1:G" + lastRow).getFormulas();
for (var i = 0; i < formulas.length; i++) {
var formula = formulas[i][0];
var pattern = new RegExp('\\b' + textToFind + '\\b', 'i');
if (formula && pattern.test(formula)) {
rowsToDelete.push(i + 1);
}
}
if (rowsToDelete.length > 0) {
rowsToDelete.reverse().forEach(function(rowIndex) {
sheet.deleteRow(rowIndex);
});
}
}
In this version, I used the getFormulas() instead of getValues() and it worked. BUT, keep in mind that when you delete rows, you are changing the numbering of all the other rows.
So if you have a bunch of rows you want to delete inside a sheet, consecutive or not, then this code will help you achieve that.
Further explanation:
I've created an empty array called rowsToDelete before the loop, and then added the row numbers of any matching rows to that array using rowsToDelete.push(i + 1).
After the loop completes, I'm checking if the rowsToDelete array has any elements using rowsToDelete.length > 0. If it does, we're reversing the order of the row numbers in the array using rowsToDelete.reverse(), and then using the forEach() method to iterate over the row numbers and delete each row in turn using sheet.deleteRow(rowIndex).
I've used the getMaxRows() method to get the maximum number of rows in the sheet, which should include all the rows in the sheet, even if they are currently empty.