简体   繁体   中英

Highlighting specific words in Google Sheets script

To sumarize the most of it, i'm trying to create an sheet to emulate an RPG game inventory. The problem i'm stuck at is "item rarity grading coloring". So the "common" item will be gray, the "rare" will be blue, the "ancient" will be red, and this is measured by "stars".

The inventory cell that is a input, the player will go: "Blades of ancient times - 5*" or "Daggers of Bleeding [5*]" (without quotes)

I came up with this:

function onEdit(event)
{
  var ss = event.range.getSheet();
  if (ss.getName() !== "z") return; // Get out quickly
  var changedCell = event.source.getActiveRange();
  var changedCellA1 = changedCell.getA1Notation();

  var c = event.value;  // We know we edited cell, just get the value
  var background = 'gray'; // Assume 1 <= c <= 2
  if (c == 2) {
    background = 'red';
  }
  else if (c == 1) {
    background = 'white'; 
  }
  changedCell.setFontColor(background);
}

But when it hits the "if (c == 2)" i just don't know how to properly get the info in the script from what i need...

if (c has or ends with "[1*]") do white text
if (c has or ends with "[2*]") do grey text

In this, if you're on the "z" sheet and edit a cell, if its 1 will be white, if its 2 will be red.

SOLUTION

  • You can use includes() method on your if-else statement. You can try this edited sample script below:

Sample Script

function onEdit(event)
{
  var ss = event.range.getSheet();
  if (ss.getName() !== "z") return; // Get out quickly
  var changedCell = event.source.getActiveRange();
  var changedCellA1 = changedCell.getA1Notation();

  var c = event.value;  // We know we edited cell, just get the value
  var background = 'gray'; // Assume 1 <= c <= 2
  if (c.includes("2")) {
    background = 'red';
  }
  else if (c.includes("1")) {
    background = 'white'; 
  }
  changedCell.setFontColor(background);
}

Test Demonstration

Test Sheet (changed background to color black for text color change visibility)

在此处输入图片说明

When the value in A1 gets edited/updated:

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM