Searching for the perfect match within Google's Apps Script

Is there a way to modify this script so it only replaces an exact match of 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

Answer №1

Problem:

  • Using String Instead of Regex Object: The issue is that a String is being used as the first argument in String#replace(), expecting a regex type execution. "/^T$/" will be seen as a string literal containing certain characters instead of a regex pattern.

Solution:

  • Remove Quotation Marks from Regex: Regex literals should not be enclosed in quotes like ".

Example #1:

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

Example #2:

You can also utilize .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);
    });
  })
);

Additional Resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please ensure all information is completed before submitting

My registration page function is alerting users to fill in all required data, but the form is still submitting incomplete information. I need it to prevent submission until all fields are filled correctly. function checkdetails() { if (document.form ...

Encountered a console error when attempting to execute a sample React JS web application

I recently started exploring React JS and decided to experiment with a simple "hello react" web application. However, when I tried to run it, I encountered the following error in the console. Warning: Calling Element.createShadowRoot() for an element that ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

Modifying the color of elements within a picture

I am in search of the perfect web technology or JavaScript library that can help me achieve a specific functionality. My aim is to change the colors of particular objects within an image. I am looking to create a tool where users can select a color, and th ...

What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with: var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random(); req.onreadystatechange = processAccessGroupRequest; req.open("GET", url, true); req.send(null); function ...

create a data structure by combining form inputs with various variables

I need help with my form: <div class="form_style"> <input name="name" type="text" id="Name" class="input username" placeholder="Username" /> <textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="Enter some text"& ...

The POST function in jQuery often returns the [Object object] result

Looking to extract a string from a PHP file using jQuery's post method. function getString(string) { return $.ajax({ type: 'POST', url: 'scripts/getstring.php', data: { 'string': string } ...

conversion of vtk files to obj format or any other file format

I am looking to convert .vtk files to .obj or .json formats. While vtk offers the vtkOBJExporter class for this purpose, I am unsure how to actually achieve this conversion. Upon installing the visualization toolkit, only a console is displayed when opened ...

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

Tips for managing a PHP post request without full knowledge of the variables to retrieve

My form allows users to dynamically add new lines using JavaScript. However, when they click the save button, I am struggling to capture and assign the new data to a variable. The current issue is that once the user adds new rows and clicks save, the rows ...

Comparing #id_gender against assigning $('#id_gender') to the variable gender

Users are required to specify their gender. HTML <form ...> <select id="id_gender" name="gender" onchange="hideMaidenName(this.value)"> <option value="M">Male</option> <option value="F">Female</option> <option value ...

Issue with fullcalendar.js: event times are not appearing on agenda view

I'm struggling to get timed events to display correctly on the agendaWeek view. The first two events, which are mine, show up as all day events instead of at their specified times. However, the last event from the documentation displays in the correct ...

Why does the child Vuex Store Object return undefined while the parent returns correctly?

I've come across some similar inquiries, but none quite fit my specific scenario. Upon logging this.$store.state.account, the expected results are displayed {__ob__: Nt} user: Object favorites_playlist: (...) firebaseI ...

The custom tooltip is not being displayed as intended

I'm currently working on customizing tooltips in angularjs google charts. My goal is to display multiple series data along with some text within the tooltip, similar to the demo showcased here. Specifically, I aim to include the legend and title of th ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Issue with jQuery Ready Event Not Triggering Following AJAX Load

Excuse me, could you help me with something? I have tried to find an answer for this issue but it is still not working. Here are my scripts: $(document).ready(function() { $('.gifs').gifplayer(); }); I also have dynamic content loaded by AJAX ...

What steps do I need to take to adjust my code so that the div function is hidden upon the second click

, I have provided my code as a beginner who is learning on the go. The code showcases a function that triggers on click and loads content accordingly. However, the desired functionality includes hiding the content on the second click and maintaining an "a ...

Changing the time zone of a browser using JavaScript or jQuery

After researching numerous discussions on the topic, it appears that changing the browser's timezone programmatically is not possible. Although the moment-timezone.js library allows us to set timezone for its objects, it does not affect the browser&ap ...

Grant the "User" the ability to modify both images and prices

I'm currently working on an art website for a relative and I am looking to provide them with the ability to log in and easily update the images of their paintings as well as adjust the pricing. Is it possible to enable this functionality? My assumptio ...

Organizing information on a chart in Google Sheets

I am looking to create a chart with sorted data from unsorted data in the sheet. For reference, here is an example: https://i.sstatic.net/8b2mN.png The desired sorting for the chart is ascending, based on compensation. Is there a way to achieve this wi ...