I want to create a function in Google Sheets that loops through an array, finds a string, and replaces the text of the string with a new value. I have code that works but it only replaces the text if the cell ONLY contains the string (ie search for "office" replace with "Office" only works if the cell only contains "office). I want to be able to replace "office" with "Office" even if the cell contains "office 867". Below is the code that works. Also, how can I get the function to search column A, row 1 to whatever? As of now, the function only finds and replaces if the values are in B2 to whatever (ie the first column A is not searched and the first row of every other row is not searched. Function works on B2 to whatever but won't work on B1, C1, D1, etc. I know it is because of the searchRange variable but I can't figure out how to set the parameters so that it searches the entire sheet (ie all columns and all rows). So here's the code I have so far. The questions I have are in the code as comments:
// This code works but ONLY if entire cell matches the string being searched for
// I want to search for all cells that contain the string even if other text is present
// So if cell contains "office 98" I want to change that to "Office 98"
// If cell contains "blg 78" I want to change that to "Building 78"
// If cell contains "space 9876" I want to change that to "Space 9876"
// Also, how do I change the var searchRange so that the range is the entire sheet?
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);
function findReplace() {
var rangeValues = searchRange.getValues();
for ( i = 0; i < lastColumn - 1; i++){
for ( j = 0 ; j < lastRow - 1; j++){
if(rangeValues[j][i] === "office"){
sheet.getRange(j+2,i+2).setValue("Office");
}else if (rangeValues[j][i] === "blg"){
sheet.getRange(j+2,i+2).setValue("Building");
}else if (rangeValues[j][i] === "space"){
sheet.getRange(j+2,i+2).setValue("Space");
};
};
};
};