0

In the continuation of the question asked HERE and a great reply by @Edvin I have following query.

The following code works great in my Google spreadsheet.

function onEdit(e) {
  if (typeof e.value != 'object') {
    if ([4, 5].indexOf(e.range.columnStart)<0) return;
    e.range.setValue(titleCase(e.value));
  }
}

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

Is there any way I can add TRIM, CLEAN, Remove extra spaces between words like functions in this code.

player0
  • 124,011
  • 12
  • 67
  • 124
Rahul
  • 13
  • 1
  • 6

1 Answers1

0

How about this answer? Please think of this as just one of several answers.

In this answer, I used the script from this thread for achieving TRIM and CLEAN. And using this function, your script was modified.

Modified script:

function onEdit(e) {
  if (typeof e.value != 'object') {
    if ([4, 5].indexOf(e.range.columnStart)<0) return;
    e.range.setValue(titleCase(e.value));
  }
}

// Modified
function titleCase(str) {
  return str.toString().split(/\b/).map(function(word) {
    return word ? cleanForGAS(word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) : '';
  }).filter(String).join(' ');
}

// This function is from https://stackoverflow.com/a/50053581
function cleanForGAS(str) {
  if (typeof str == "string") {
    var escaped = escape(str.trim());
    for (var i = 0; i <= 31; i++) {
      var s = i.toString(16);
      var re = new RegExp("%" + (s.length == 1 ? "0" + s : s).toUpperCase(), "g");
      escaped = escaped.replace(re, "");
    }
    var remove = ["%7F", "%81", "%8D", "%8F", "%90", "%9D"];
    remove.forEach(function(e) {
      var re = new RegExp(e, "g");
      escaped = escaped.replace(re, "");
    });
    return unescape(escaped).trim();
  } else {
    return str;
  }
}

If I misunderstood your question and this was not the result you want, I apologize.

Tanaike
  • 181,128
  • 11
  • 97
  • 165