Warm tip: This article is reproduced from stackoverflow.com, please click
google-apps-script google-sheets javascript regex

Googles Apps Script exact match

发布于 2020-03-27 10:23:39

I'm using this script but it's replacing every instance of a T, A, etc. How do I get it to only replace an exact match? Only if it's the letter T and nothing else.

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Underlevel");
  //  get the current data range values as an array
  //  Fewer calls to access the sheet -> lower overhead 
  var values = sheet.getDataRange().getValues();  

  // Replace
  replaceInSheet(values, "/^T$/", '=image("https://i.imgur.com/Dxl893F.png")');
  replaceInSheet(values, 'A', '=image("https://i.imgur.com/omc7F9l.png")');
  replaceInSheet(values, 'R', '=image("https://i.imgur.com/12ZmSp3.png")');
  replaceInSheet(values, 'M', '=image("https://i.imgur.com/kh7RqBD.png")');
  replaceInSheet(values, 'H', '=image("https://i.imgur.com/u0O7fsS.png")');
  replaceInSheet(values, 'F', '=image("https://i.imgur.com/Hbs3TuP.png")');

  // Write all updated values to the sheet, at once
  sheet.getDataRange().setValues(values);
}

function replaceInSheet(values, to_replace, replace_with) {
  //loop over the rows in the array
  for(var row in values){
    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value) {
      return original_value.toString().replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }
}

Thank you :D

Questioner
Ryan King
Viewed
165
TheMaster 2019-07-03 22:34

Issue:

  • String type instead of Regex object: You're providing a String as first argument to String#replace() and expecting a regex type execution. "/^T$/" will be interpreted as a string literal that starts with /, contains ^,T, and $ and ends with /.

Solution:

  • Unquoted Regex: Regex literal shouldn't be quoted with".

Snippet#1:

/^T$/    //or new RegExp('^T$')

Snippet#2:

You can also just use .replace() with a replacer function directly.

var range = sheet.getDataRange();
var replaceObj = {
  //to_replace: imgur id
  T: 'Dxl893F',
  A: 'omc7F9l',
};
var regex = new RegExp('^(' + Object.keys(replaceObj).join('|') + ')$', 'g');// /^(T|A)$/
function replacer(match) {
  return '=image("https://i.imgur.com/' + replaceObj[match] + '.png")';
}
range.setValues(
  range.getValues().map(function(row) {
    return row.map(function(original_value) {
      return original_value.toString().replace(regex, replacer);
    });
  })
);

References: