James Woods
James Woods

Reputation: 35

Google Sheets onEdit capitalize script function

I appreciate the collective wisdom of the group.

I found these snippets of code on the internet and have tried to adopt them to my situation and by no means intend to plagiarize anyone ...

I want to capitalize every word in a cell. I invoke the follow script from my onEdit(e) function. Doesn't do anything. This just doesn't look like right and obviously I am missing important data ...

function onEdit(e) { TitleCase(e); }

function TitleCase(e) {
  return e.toString().split(/\b/).map(function (word) {
    return e ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : '';
  }).join('');
}

I am a newbie and I really appreciate any guidance.

Jim

Upvotes: 2

Views: 84

Answers (1)

Tanaike
Tanaike

Reputation: 201438

Modification points:

  • When you want to run the script of TitleCase from the simple trigger of OnEdit, it is required to directly put the values to the cell.

  • From your script, e is the event object. So using this object, the value is retrieved and put it to the cell.

  • In your script of TitleCase, I think that it is almost the correct. But, I think that e of return e ? e.charAt(0).toUpperCase() + e.slice(1).toLowerCase() : ''; should be word.

  • From your additinal request of How would it be further modified to only perform this for one specific column?, in this case, it is required to check the edited column.

When above points are reflected to your script, it becomes as follows.

Modified script:

When you use this script, please put the text to a cell. By this, the script is run.

function onEdit(e) {TitleCase(e);}

function TitleCase(e) {
  const columnNumber = 1; // Please set the specific column number. For example, 1 is the column "A".
  const range = e.range;
  if (range.getColumn() != columnNumber) return;
  const value = range.getValue().toString().split(/\b/).map(function(word) {
    return word ? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() : '';
  }).join('');
  range.setValue(value);
}

References:

Upvotes: 1

Related Questions